Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
36.11% covered (danger)
36.11%
942 / 2609
5.77% covered (danger)
5.77%
3 / 52
CRAP
0.00% covered (danger)
0.00%
0 / 1
AppController
36.06% covered (danger)
36.06%
940 / 2607
5.77% covered (danger)
5.77%
3 / 52
209383.67
0.00% covered (danger)
0.00%
0 / 1
 processSGF
73.58% covered (warning)
73.58%
39 / 53
0.00% covered (danger)
0.00%
0 / 1
19.15
 xFlip
75.00% covered (warning)
75.00%
3 / 4
0.00% covered (danger)
0.00%
0 / 1
2.06
 yFlip
75.00% covered (warning)
75.00%
3 / 4
0.00% covered (danger)
0.00%
0 / 1
2.06
 getInitialPositionEnd
62.50% covered (warning)
62.50%
5 / 8
0.00% covered (danger)
0.00%
0 / 1
3.47
 getInitialPosition
50.00% covered (danger)
50.00%
10 / 20
0.00% covered (danger)
0.00%
0 / 1
10.50
 getInvisibleSets
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
12
 getDeletedSets
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
12
 startPageUpdate
88.89% covered (warning)
88.89%
16 / 18
0.00% covered (danger)
0.00%
0 / 1
5.03
 uotd
0.00% covered (danger)
0.00%
0 / 157
0.00% covered (danger)
0.00%
0 / 1
2070
 deleteUnusedStatuses
0.00% covered (danger)
0.00%
0 / 40
0.00% covered (danger)
0.00%
0 / 1
72
 saveSolvedNumber
0.00% covered (danger)
0.00%
0 / 32
0.00% covered (danger)
0.00%
0 / 1
156
 convertEloToXp
75.00% covered (warning)
75.00%
3 / 4
0.00% covered (danger)
0.00%
0 / 1
2.06
 resetUserElos
0.00% covered (danger)
0.00%
0 / 14
0.00% covered (danger)
0.00%
0 / 1
12
 handleContribution
52.94% covered (warning)
52.94%
9 / 17
0.00% covered (danger)
0.00%
0 / 1
2.42
 getAllTags
96.55% covered (success)
96.55%
28 / 29
0.00% covered (danger)
0.00%
0 / 1
7
 deleteUserBoards
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 halfXP
0.00% covered (danger)
0.00%
0 / 11
0.00% covered (danger)
0.00%
0 / 1
30
 getNewTsumego
0.00% covered (danger)
0.00%
0 / 13
0.00% covered (danger)
0.00%
0 / 1
12
 publishSingle
0.00% covered (danger)
0.00%
0 / 45
0.00% covered (danger)
0.00%
0 / 1
30
 getTsumegoOfTheDay
0.00% covered (danger)
0.00%
0 / 104
0.00% covered (danger)
0.00%
0 / 1
1190
 ratingMatch
0.00% covered (danger)
0.00%
0 / 62
0.00% covered (danger)
0.00%
0 / 1
992
 rating2
0.00% covered (danger)
0.00%
0 / 22
0.00% covered (danger)
0.00%
0 / 1
132
 encrypt
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
1
 decrypt
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
2
 checkPictureLarge
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
12
 checkPicture
66.67% covered (warning)
66.67%
2 / 3
0.00% covered (danger)
0.00%
0 / 1
3.33
 getTsumegoRankx
0.00% covered (danger)
0.00%
0 / 42
0.00% covered (danger)
0.00%
0 / 1
506
 adjustElo
0.00% covered (danger)
0.00%
0 / 23
0.00% covered (danger)
0.00%
0 / 1
132
 getTsumegoElo
60.38% covered (warning)
60.38%
32 / 53
0.00% covered (danger)
0.00%
0 / 1
95.70
 getTsumegoRankVal
0.00% covered (danger)
0.00%
0 / 41
0.00% covered (danger)
0.00%
0 / 1
506
 getTsumegoRankMax
0.00% covered (danger)
0.00%
0 / 41
0.00% covered (danger)
0.00%
0 / 1
506
 saveDanSolveCondition
100.00% covered (success)
100.00%
18 / 18
100.00% covered (success)
100.00%
1 / 1
7
 updateSprintCondition
94.44% covered (success)
94.44%
17 / 18
0.00% covered (danger)
0.00%
0 / 1
4.00
 updateGoldenCondition
94.12% covered (success)
94.12%
16 / 17
0.00% covered (danger)
0.00%
0 / 1
3.00
 setPotionCondition
0.00% covered (danger)
0.00%
0 / 14
0.00% covered (danger)
0.00%
0 / 1
6
 updateGems
3.85% covered (danger)
3.85%
4 / 104
0.00% covered (danger)
0.00%
0 / 1
2183.48
 checkProblemNumberAchievements
42.39% covered (danger)
42.39%
39 / 92
0.00% covered (danger)
0.00%
0 / 1
166.38
 checkDanSolveAchievements
54.91% covered (warning)
54.91%
95 / 173
0.00% covered (danger)
0.00%
0 / 1
354.78
 checkForLocked
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
20
 checkNoErrorAchievements
81.54% covered (warning)
81.54%
53 / 65
0.00% covered (danger)
0.00%
0 / 1
18.82
 checkTimeModeAchievements
35.40% covered (danger)
35.40%
40 / 113
0.00% covered (danger)
0.00%
0 / 1
2273.83
 checkRatingAchievements
54.44% covered (warning)
54.44%
49 / 90
0.00% covered (danger)
0.00%
0 / 1
95.92
 checkLevelAchievements
72.22% covered (warning)
72.22%
65 / 90
0.00% covered (danger)
0.00%
0 / 1
42.63
 checkSetCompletedAchievements
19.72% covered (danger)
19.72%
14 / 71
0.00% covered (danger)
0.00%
0 / 1
166.54
 setAchievementSpecial
0.00% covered (danger)
0.00%
0 / 184
0.00% covered (danger)
0.00%
0 / 1
4160
 checkSetAchievements
18.10% covered (danger)
18.10%
40 / 221
0.00% covered (danger)
0.00%
0 / 1
2533.09
 getXPJump
0.00% covered (danger)
0.00%
0 / 15
0.00% covered (danger)
0.00%
0 / 1
72
 updateXP
75.00% covered (warning)
75.00%
36 / 48
0.00% covered (danger)
0.00%
0 / 1
18.52
 getPartitionRange
0.00% covered (danger)
0.00%
0 / 22
0.00% covered (danger)
0.00%
0 / 1
56
 handleSearchSettings
100.00% covered (success)
100.00%
13 / 13
100.00% covered (success)
100.00%
1 / 1
2
 signIn
83.33% covered (warning)
83.33%
5 / 6
0.00% covered (danger)
0.00%
0 / 1
2.02
 beforeFilter
83.58% covered (warning)
83.58%
280 / 335
0.00% covered (danger)
0.00%
0 / 1
93.31
 afterFilter
n/a
0 / 0
n/a
0 / 0
1
1<?php
2
3App::uses('Auth', 'Utility');
4App::uses('TsumegoFilters', 'Utility');
5
6class AppController extends Controller {
7    public $viewClass = 'App';
8
9    public $components = [
10        'Session',
11        //'DebugKit.Toolbar',
12        'Flash',
13        'PlayResultProcessor',
14        'TimeMode',
15    ];
16
17    public static function processSGF($sgf) {
18        $aw = strpos($sgf, 'AW');
19        $ab = strpos($sgf, 'AB');
20        $boardSizePos = strpos($sgf, 'SZ');
21        $boardSize = 19;
22        $sgfArr = str_split($sgf);
23        if ($boardSizePos !== false) {
24            $boardSize = $sgfArr[$boardSizePos + 3] . '' . $sgfArr[$boardSizePos + 4];
25        }
26        if (substr($boardSize, 1) == ']') {
27            $boardSize = substr($boardSize, 0, 1);
28        }
29
30        $black = AppController::getInitialPosition($ab, $sgfArr, 'x');
31        $white = AppController::getInitialPosition($aw, $sgfArr, 'o');
32        $stones = array_merge($black, $white);
33
34        $board = [];
35        for ($i = 0; $i < 19; $i++) {
36            $board[$i] = [];
37            for ($j = 0; $j < 19; $j++) {
38                $board[$i][$j] = '-';
39            }
40        }
41        $lowestX = 18;
42        $lowestY = 18;
43        $highestX = 0;
44        $highestY = 0;
45        $stonesCount = count($stones);
46        for ($i = 0; $i < $stonesCount; $i++) {
47            if ($stones[$i][0] < $lowestX) {
48                $lowestX = $stones[$i][0];
49            }
50            if ($stones[$i][0] > $highestX) {
51                $highestX = $stones[$i][0];
52            }
53            if ($stones[$i][1] < $lowestY) {
54                $lowestY = $stones[$i][1];
55            }
56            if ($stones[$i][1] > $highestY) {
57                $highestY = $stones[$i][1];
58            }
59        }
60        if (18 - $lowestX < $lowestX) {
61            $stones = AppController::xFlip($stones);
62        }
63        if (18 - $lowestY < $lowestY) {
64            $stones = AppController::yFlip($stones);
65        }
66        $highestX = 0;
67        $highestY = 0;
68        $stonesCount = count($stones);
69        for ($i = 0; $i < $stonesCount; $i++) {
70            if ($stones[$i][0] > $highestX) {
71                $highestX = $stones[$i][0];
72            }
73            if ($stones[$i][1] > $highestY) {
74                $highestY = $stones[$i][1];
75            }
76            $board[$stones[$i][0]][$stones[$i][1]] = $stones[$i][2];
77        }
78        $tInfo = [];
79        $tInfo[0] = $highestX;
80        $tInfo[1] = $highestY;
81        $arr = [];
82        $arr[0] = $board;
83        $arr[1] = $stones;
84        $arr[2] = $tInfo;
85        $arr[3] = $boardSize;
86
87        return $arr;
88    }
89
90    public static function xFlip($stones) {
91        $stonesCount = count($stones);
92        for ($i = 0; $i < $stonesCount; $i++) {
93            $stones[$i][0] = 18 - $stones[$i][0];
94        }
95
96        return $stones;
97    }
98
99    public static function yFlip($stones) {
100        $stonesCount = count($stones);
101        for ($i = 0; $i < $stonesCount; $i++) {
102            $stones[$i][1] = 18 - $stones[$i][1];
103        }
104
105        return $stones;
106    }
107
108    public static function getInitialPositionEnd($pos, $sgfArr) {
109        $endCondition = 0;
110        $currentPos1 = $pos + 2;
111        $currentPos2 = $pos + 5;
112        while ($sgfArr[$currentPos1] == '[' && $sgfArr[$currentPos2] == ']') {
113            $endCondition = $currentPos2;
114            $currentPos1 += 4;
115            $currentPos2 += 4;
116        }
117
118        return $endCondition;
119    }
120
121    public static function getInitialPosition($pos, $sgfArr, $color) {
122        $arr = [];
123        $end = AppController::getInitialPositionEnd($pos, $sgfArr);
124        for ($i = $pos + 2; $i < $end; $i++) {
125            if ($sgfArr[$i] != '[' && $sgfArr[$i] != ']') {
126                array_push($arr, strtolower($sgfArr[$i]));
127            }
128        }
129        $alphabet = array_flip(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']);
130        $xy = true;
131        $arr2 = [];
132        $c = 0;
133        $arrCount = count($arr);
134        for ($i = 0; $i < $arrCount; $i++) {
135            $arr[$i] = $alphabet[$arr[$i]];
136            if ($xy) {
137                $arr2[$c] = [];
138                $arr2[$c][0] = $arr[$i];
139            } else {
140                $arr2[$c][1] = $arr[$i];
141                $arr2[$c][2] = $color;
142                $c++;
143            }
144            $xy = !$xy;
145        }
146
147        return $arr2;
148    }
149
150    protected function getInvisibleSets() {
151        $this->loadModel('Set');
152        $invisibleSets = [];
153        $in = $this->Set->find('all', ['conditions' => ['public' => 0]]);
154        if (!$in) {
155            $in = [];
156        }
157        foreach ($in as $item) {
158            $invisibleSets[] = $item['Set']['id'];
159        }
160
161        return $invisibleSets;
162    }
163
164    protected function getDeletedSets() {
165        $dSets = [];
166        $de = $this->Set->find('all', ['conditions' => ['public' => -1]]);
167        if (!$de) {
168            $de = [];
169        }
170        foreach ($de as $item) {
171            $dSets[] = $item['Set']['id'];
172        }
173
174        return $dSets;
175    }
176
177    /**
178     * @return void
179     */
180    public static function startPageUpdate() {
181        $str = '';
182        $latest = ClassRegistry::init('AchievementStatus')->find('all', ['limit' => 7, 'order' => 'created DESC']);
183        if (!$latest) {
184            $latest = [];
185        }
186        $latestCount = count($latest);
187        for ($i = 0; $i < $latestCount; $i++) {
188            $a = ClassRegistry::init('Achievement')->findById($latest[$i]['AchievementStatus']['achievement_id']);
189            $u = ClassRegistry::init('User')->findById($latest[$i]['AchievementStatus']['user_id']);
190            if (substr($u['User']['name'], 0, 3) == 'g__' && $u['User']['external_id'] != null) {
191                $startPageUser = AppController::checkPicture($u);
192            } else {
193                $startPageUser = $u['User']['name'];
194            }
195            $latest[$i]['AchievementStatus']['name'] = $a['Achievement']['name'];
196            $latest[$i]['AchievementStatus']['color'] = $a['Achievement']['color'];
197            $latest[$i]['AchievementStatus']['image'] = $a['Achievement']['image'];
198            $latest[$i]['AchievementStatus']['user'] = $startPageUser;
199            $str .= '<div class="quote1"><div class="quote1a"><a href="/achievements/view/' . $a['Achievement']['id'] . '"><img src="/img/' . $a['Achievement']['image'] . '.png" width="34px"></a></div>';
200            $str .= '<div class="quote1b">Achievement gained by ' . $startPageUser . ':<br><div class=""><b>' . $a['Achievement']['name'] . '</b></div></div></div>';
201        }
202        file_put_contents('mainPageAjax.txt', $str);
203    }
204
205    /**
206     * @return void
207     */
208    protected function uotd() { //routine1
209        $this->loadModel('User');
210        $this->loadModel('DayRecord');
211        $this->loadModel('TsumegoAttempt');
212        $this->loadModel('Achievement');
213        $this->loadModel('AchievementCondition');
214        $today = date('Y-m-d');
215        $ux2 = $this->User->find('all', [
216            'limit' => '8',
217            'order' => 'reuse3 DESC',
218            'conditions' => [
219                'NOT' => ['id' => [33]],
220            ],
221        ]);
222        if (!$ux2) {
223            $ux2 = [];
224        }
225        $last = $this->DayRecord->find('all', ['limit' => '7', 'order' => 'date DESC']);
226        if (!$last) {
227            $last = [];
228        }
229        $lastUotds = [];
230        $lastUsers = [];
231        foreach ($last as $item) {
232            $lastUotds[] = $item['DayRecord']['user_id'];
233        }
234        foreach ($ux2 as $item) {
235            $lastUsers[] = $item['User']['id'];
236        }
237        $resultUser = 72;
238        $lastUsersCount = count($lastUsers);
239        for ($i = 0; $i < $lastUsersCount; $i++) {
240            $foundUser = false;
241            $lastUotdsCount = count($lastUotds);
242            for ($j = 0; $j < $lastUotdsCount; $j++) {
243                if ($lastUsers[$i] == $lastUotds[$j]) {
244                    $foundUser = true;
245                }
246            }
247            if (!$foundUser) {
248                $resultUser = $lastUsers[$i];
249
250                break;
251            }
252        }
253        $ux = $this->User->findById($resultUser);
254
255        $recentlyUsed = [];
256        $d = 1;
257        while ($d <= 10) {
258            $ru = $this->DayRecord->find('first', ['conditions' => ['date' => date('Y-m-d', strtotime('-' . $d . ' days'))]]);
259            if ($ru) {
260                array_push($recentlyUsed, $ru);
261            }
262            $d++;
263        }
264        $currentQuote = 'q01';
265        $newQuote = 'q01';
266        $quoteChosen = false;
267        while (!$quoteChosen) {
268            $newQuote = rand(1, 45);
269            if ($newQuote < 10) {
270                $newQuote = 'q0' . $newQuote;
271            } else {
272                $newQuote = 'q' . $newQuote;
273            }
274
275            $f = false;
276            $recentlyUsedCount = count($recentlyUsed);
277            for ($i = 0; $i < $recentlyUsedCount; $i++) {
278                if ($newQuote == $recentlyUsed[$i]['DayRecord']['quote']) {
279                    $f = true;
280                }
281            }
282            if (!$f) {
283                $quoteChosen = true;
284            }
285        }
286        $currentQuote = $newQuote;
287        $dayUserRand = 1;
288        $uotdChosen = false;
289        while (!$uotdChosen) {
290            $dayUserRand = rand(1, 39);
291            $f = false;
292            $recentlyUsedCount = count($recentlyUsed);
293            for ($i = 0; $i < $recentlyUsedCount; $i++) {
294                if ($dayUserRand == $recentlyUsed[$i]['DayRecord']['userbg']) {
295                    $f = true;
296                }
297            }
298            if (!$f) {
299                $uotdChosen = true;
300            }
301        }
302        $activity = $this->TsumegoAttempt->find('all', ['limit' => 40000, 'conditions' => ['DATE(TsumegoAttempt.created)' => date('Y-m-d', strtotime('yesterday'))]]);
303        if (!$activity) {
304            $activity = [];
305        }
306        $visitedProblems = count($activity);
307
308        //how many users today
309        $usersNum = [];
310        $activity = $this->User->find('all', ['limit' => 400, 'order' => 'created DESC']);
311        if (!$activity) {
312            $activity = [];
313        }
314        $activityCount = count($activity);
315        for ($i = 0; $i < $activityCount; $i++) {
316            $a = new DateTime($activity[$i]['User']['created']);
317            if ($a->format('Y-m-d') == $today) {
318                array_push($usersNum, $activity[$i]['User']);
319            }
320        }
321        $gemRand1 = rand(0, 2);
322        $gemRand2 = rand(0, 2);
323        $gemRand3 = rand(0, 2);
324
325        $arch1 = ClassRegistry::init('Achievement')->findById(111);
326        if ($gemRand1 == 0) {
327            $arch1['Achievement']['description'] = 'Has a chance to trigger once a day on an easy ddk problem.';
328        } elseif ($gemRand1 == 1) {
329            $arch1['Achievement']['description'] = 'Has a chance to trigger once a day on a regular ddk problem.';
330        } elseif ($gemRand1 == 2) {
331            $arch1['Achievement']['description'] = 'Has a chance to trigger once a day on a difficult ddk problem.';
332        }
333        ClassRegistry::init('Achievement')->save($arch1);
334        $arch2 = ClassRegistry::init('Achievement')->findById(112);
335        if ($gemRand2 == 0) {
336            $arch2['Achievement']['description'] = 'Has a chance to trigger once a day on an easy sdk problem.';
337        } elseif ($gemRand2 == 1) {
338            $arch2['Achievement']['description'] = 'Has a chance to trigger once a day on a regular sdk problem.';
339        } elseif ($gemRand2 == 2) {
340            $arch2['Achievement']['description'] = 'Has a chance to trigger once a day on a difficult sdk problem.';
341        }
342        ClassRegistry::init('Achievement')->save($arch2);
343        $arch3 = ClassRegistry::init('Achievement')->findById(113);
344        if ($gemRand3 == 0) {
345            $arch3['Achievement']['description'] = 'Has a chance to trigger once a day on an easy dan problem.';
346        } elseif ($gemRand3 == 1) {
347            $arch3['Achievement']['description'] = 'Has a chance to trigger once a day on a regular dan problem.';
348        } elseif ($gemRand3 == 2) {
349            $arch3['Achievement']['description'] = 'Has a chance to trigger once a day on a difficult dan problem.';
350        }
351        ClassRegistry::init('Achievement')->save($arch3);
352
353        $this->DayRecord->create();
354        $dateUser = [];
355        $dateUser['DayRecord']['user_id'] = $ux['User']['id'];
356        $dateUser['DayRecord']['date'] = $today;
357        $dateUser['DayRecord']['solved'] = $ux['User']['reuse3'];
358        $dateUser['DayRecord']['quote'] = $currentQuote;
359        $dateUser['DayRecord']['userbg'] = $dayUserRand;
360        $dateUser['DayRecord']['tsumego'] = $this->getTsumegoOfTheDay();
361        $dateUser['DayRecord']['newTsumego'] = $this->getNewTsumego();
362        $dateUser['DayRecord']['usercount'] = count($usersNum);
363        $dateUser['DayRecord']['visitedproblems'] = $visitedProblems;
364        $dateUser['DayRecord']['gems'] = $gemRand1 . '-' . $gemRand2 . '-' . $gemRand3;
365        $dateUser['DayRecord']['gemCounter1'] = 0;
366        $dateUser['DayRecord']['gemCounter2'] = 0;
367        $dateUser['DayRecord']['gemCounter3'] = 0;
368        $this->DayRecord->save($dateUser);
369
370        ClassRegistry::init('AchievementCondition')->create();
371        $achievementCondition = [];
372        $achievementCondition['AchievementCondition']['user_id'] = $ux['User']['id'];
373        $achievementCondition['AchievementCondition']['set_id'] = 0;
374        $achievementCondition['AchievementCondition']['category'] = 'uotd';
375        $achievementCondition['AchievementCondition']['value'] = 1;
376        ClassRegistry::init('AchievementCondition')->save($achievementCondition);
377
378        //delete duplicated DayRecords
379        $dr = $this->DayRecord->find('all');
380        if (!$dr) {
381            $dr = [];
382        }
383        $duplicates = [];
384        $drCount = count($dr);
385        for ($i = 0; $i < $drCount; $i++) {
386            $alreadyFound = [];
387            for ($j = 0; $j < $drCount; $j++) {
388                if ($i != $j && $dr[$j]['DayRecord']['date'] == $dr[$i]['DayRecord']['date']) {
389                    $found = false;
390                    $alreadyFoundCount = count($alreadyFound);
391                    for ($k = 0; $k < $alreadyFoundCount; $k++) {
392                        if ($alreadyFound[$k]['DayRecord']['id'] == $dr[$i]['DayRecord']['id'] || $alreadyFound[$k]['DayRecord']['id'] == $dr[$j]['DayRecord']['id']) {
393                            $found = true;
394                        }
395                    }
396                    if (!$found) {
397                        array_push($duplicates, $dr[$i]['DayRecord']['date']);
398                        array_push($alreadyFound, $dr[$i]);
399                    }
400                }
401            }
402        }
403        $duplicates = array_count_values($duplicates);
404        foreach ($duplicates as $key => $value) {
405            while ($duplicates[$key] > 1) {
406                $drd = $this->DayRecord->find('first', ['conditions' => ['date' => $key]]);
407                if ($drd) {
408                    $this->DayRecord->delete($drd['DayRecord']['id']);
409                }
410                $duplicates[$key]--;
411            }
412        }
413    }
414
415    public static function deleteUnusedStatuses(int $uid): void {
416        $s = ClassRegistry::init('Set')->find('all', [
417            'conditions' => [
418                'OR' => [
419                    ['public' => 1],
420                    ['public' => 0],
421                ],
422            ],
423        ]) ?: [];
424        $ids = [];
425        $sCount = count($s);
426        for ($i = 0; $i < $sCount; $i++) {
427            $tSet = TsumegoUtil::collectTsumegosFromSet($s[$i]['Set']['id']);
428            foreach ($tSet as $item) {
429                $ids[] = $item['Tsumego']['id'];
430            }
431        }
432        $ut = ClassRegistry::init('TsumegoStatus')->find('all', [
433            'conditions' => [
434                'user_id' => $uid,
435                'NOT' => [
436                    'tsumego_id' => $ids,
437                ],
438            ],
439        ]);
440        if (!$ut) {
441            $ut = [];
442        }
443        $utCount = count($ut);
444        for ($i = 0; $i < $utCount; $i++) {
445            $test1 = ClassRegistry::init('Tsumego')->findById($ut[$i]['TsumegoStatus']['tsumego_id']);
446            $test2 = ClassRegistry::init('SetConnection')->find('first', ['conditions' => ['tsumego_id' => $test1['Tsumego']['id']]]);
447            if (!$test2) {
448                ClassRegistry::init('TsumegoStatus')->delete($ut[$i]['TsumegoStatus']['id']);
449
450                continue;
451            }
452            $test3 = ClassRegistry::init('Set')->find('first', [
453                'id' => $test2['SetConnection']['set_id'],
454                'OR' => [
455                    ['public' => 1],
456                    ['public' => 0],
457                ],
458            ]);
459            if ($test3 == null) {
460                ClassRegistry::init('TsumegoStatus')->delete($ut[$i]['TsumegoStatus']['id']);
461            }
462        }
463    }
464
465    protected function saveSolvedNumber($uid) {
466        $this->loadModel('User');
467        $this->loadModel('TsumegoStatus');
468        $this->loadModel('Set');
469        $this->loadModel('SetConnection');
470
471        $solvedUts2 = 0;
472        $tsumegos = $this->SetConnection->find('all');
473        if (!$tsumegos) {
474            $tsumegos = [];
475        }
476        $uts = $this->TsumegoStatus->find('all', ['order' => 'created DESC', 'conditions' => ['user_id' => $uid]]);
477        if (!$uts) {
478            $uts = [];
479        }
480        $setKeys = [];
481        $setArray = $this->Set->find('all', ['conditions' => ['public' => 1]]);
482        if (!$setArray) {
483            $setArray = [];
484        }
485
486        $setArrayCount = count($setArray);
487        for ($i = 0; $i < $setArrayCount; $i++) {
488            $setKeys[$setArray[$i]['Set']['id']] = $setArray[$i]['Set']['id'];
489        }
490
491        $scs = [];
492        $tsumegosCount = count($tsumegos);
493        for ($j = 0; $j < $tsumegosCount; $j++) {
494            if (!isset($scs[$tsumegos[$j]['SetConnection']['tsumego_id']])) {
495                $scs[$tsumegos[$j]['SetConnection']['tsumego_id']] = 1;
496            } else {
497                $scs[$tsumegos[$j]['SetConnection']['tsumego_id']]++;
498            }
499        }
500        $utsCount = count($uts);
501        for ($j = 0; $j < $utsCount; $j++) {
502            if ($uts[$j]['TsumegoStatus']['status'] == 'S' || $uts[$j]['TsumegoStatus']['status'] == 'W' || $uts[$j]['TsumegoStatus']['status'] == 'C') {
503                if (isset($scs[$uts[$j]['TsumegoStatus']['tsumego_id']])) {
504                    $solvedUts2 += $scs[$uts[$j]['TsumegoStatus']['tsumego_id']];
505                }
506            }
507        }
508        Auth::getUser()['solved'] = $solvedUts2;
509        Auth::saveUser();
510
511        return $solvedUts2;
512    }
513
514    public static function convertEloToXp($elo) {
515        $xp = round(pow($elo / 100, 1.55) - 6);
516        if ($xp < 10) {
517            $xp = 10;
518        }
519
520        return $xp;
521    }
522
523    /**
524     * @return void
525     */
526    protected function resetUserElos() {
527        $this->loadModel('User');
528
529        $u = $this->User->find('all', [
530            'conditions' => [
531                'id >=' => 15000,
532                'id <=' => 19000,
533            ],
534        ]);
535        if (!$u) {
536            $u = [];
537        }
538
539        $uCount = count($u);
540        for ($i = 0; $i < $uCount; $i++) {
541            $u[$i]['User']['rating'] = 900;
542            $u[$i]['User']['solved2'] = 0;
543            $this->User->save($u[$i]);
544        }
545    }
546
547    /**
548     * @param int $uid User ID
549     * @param string $action Action type
550     *
551     * @return void
552     */
553    public static function handleContribution($uid, $action) {
554        $uc = ClassRegistry::init('UserContribution')->find('first', ['conditions' => ['user_id' => $uid]]);
555        if ($uc == null) {
556            $uc = [];
557            $uc['UserContribution']['user_id'] = $uid;
558            $uc['UserContribution']['added_tag'] = 0;
559            $uc['UserContribution']['created_tag'] = 0;
560            $uc['UserContribution']['made_proposal'] = 0;
561            $uc['UserContribution']['reviewed'] = 0;
562            $uc['UserContribution']['score'] = 0;
563            ClassRegistry::init('UserContribution')->create();
564        }
565        $uc['UserContribution'][$action] += 1;
566        $uc['UserContribution']['score']
567        = $uc['UserContribution']['added_tag']
568        + $uc['UserContribution']['created_tag'] * 3
569        + $uc['UserContribution']['made_proposal'] * 5
570        + $uc['UserContribution']['reviewed'] * 2;
571        ClassRegistry::init('UserContribution')->save($uc);
572    }
573
574    public static function getAllTags($not) {
575        $a = [];
576        $notApproved = ClassRegistry::init('TagName')->find('all', ['conditions' => ['approved' => 0]]);
577        if (!$notApproved) {
578            $notApproved = [];
579        }
580        $notCount = count($not);
581        for ($i = 0; $i < $notCount; $i++) {
582            array_push($a, $not[$i]['Tag']['tag_name_id']);
583        }
584        $notApprovedCount = count($notApproved);
585        for ($i = 0; $i < $notApprovedCount; $i++) {
586            array_push($a, $notApproved[$i]['TagName']['id']);
587        }
588        $tn = ClassRegistry::init('TagName')->find('all', [
589            'conditions' => [
590                'NOT' => ['id' => $a],
591            ],
592        ]);
593        if (!$tn) {
594            $tn = [];
595        }
596        $sorted = [];
597        $keys = [];
598        $tnCount = count($tn);
599        for ($i = 0; $i < $tnCount; $i++) {
600            array_push($sorted, $tn[$i]['TagName']['name']);
601            $keys[$tn[$i]['TagName']['name']] = $tn[$i];
602        }
603        sort($sorted);
604        $s2 = [];
605        $sortedCount = count($sorted);
606        for ($i = 0; $i < $sortedCount; $i++) {
607            array_push($s2, $keys[$sorted[$i]]);
608        }
609
610        return $s2;
611    }
612
613    /**
614     * @return void
615     */
616    protected function deleteUserBoards() {
617        $this->loadModel('UserBoard');
618        $this->UserBoard->deleteAll(['1 = 1']);
619    }
620
621    /**
622     * @return void
623     */
624    protected function halfXP() {
625        $this->loadModel('TsumegoStatus');
626        $this->loadModel('DayRecord');
627        $week = $this->TsumegoStatus->find('all', ['order' => 'created DESC', 'conditions' => ['status' => 'S']]);
628        if (!$week) {
629            $week = [];
630        }
631        $oneWeek = date('Y-m-d H:i:s', strtotime('-7 days'));
632        $weekCount = count($week);
633        for ($i = 0; $i < $weekCount; $i++) {
634            if ($week[$i]['TsumegoStatus']['created'] < $oneWeek) {
635                if ($week[$i]['TsumegoStatus']['status'] == 'S') {
636                    $week[$i]['TsumegoStatus']['status'] = 'W';
637                    //$this->TsumegoStatus->save($week[$i]);
638                }
639            }
640        }
641    }
642
643    protected function getNewTsumego() {
644        $this->loadModel('Schedule');
645        $date = date('Y-m-d', strtotime('today'));
646        $s = $this->Schedule->find('all', ['conditions' => ['date' => $date]]);
647        if (!$s) {
648            $s = [];
649        }
650        $id = 0;
651        $sCount = count($s);
652        for ($i = 0; $i < $sCount; $i++) {
653            $id = $this->publishSingle($s[$i]['Schedule']['tsumego_id'], $s[$i]['Schedule']['set_id'], $s[$i]['Schedule']['date']);
654            $s[$i]['Schedule']['tsumego_id'] = $id;
655            $s[$i]['Schedule']['published'] = 1;
656            $this->Schedule->save($s[$i]);
657        }
658
659        return $id;
660    }
661
662    protected function publishSingle($t = null, $to = null, $date = null) {
663        $this->loadModel('Tsumego');
664        $this->loadModel('Sgf');
665        $this->loadModel('SetConnection');
666        $this->loadModel('PublishDate');
667        $ts = $this->Tsumego->findById($t);
668
669        $id = $this->Tsumego->find('first', ['limit' => 1, 'order' => 'id DESC']);
670        if (!$id) {
671            return null;
672        }
673        $id = $id['Tsumego']['id'];
674        $id += 1;
675
676        $scT = $this->SetConnection->find('first', ['conditions' => ['tsumego_id' => $ts['Tsumego']['id']]]);
677        if ($scT != null) {
678            $scT['SetConnection']['set_id'] = $to;
679            $scT['SetConnection']['tsumego_id'] = $id;
680            $scT['SetConnection']['num'] = $ts['Tsumego']['num'];
681            $this->SetConnection->save($scT);
682        } else {
683            $scT = [];
684            $scT['SetConnection']['set_id'] = $to;
685            $scT['SetConnection']['tsumego_id'] = $id;
686            $scT['SetConnection']['num'] = $ts['Tsumego']['num'];
687            $this->SetConnection->create();
688            $this->SetConnection->save($scT);
689        }
690
691        $sid = $ts['Tsumego']['id'];
692        $ts['Tsumego']['id'] = $id;
693        $ts['Tsumego']['created'] = $date . ' 22:00:00';
694        $ts['Tsumego']['solved'] = 0;
695        $ts['Tsumego']['failed'] = 0;
696        $ts['Tsumego']['userWin'] = 0;
697        $ts['Tsumego']['userLoss'] = 0;
698        $this->Tsumego->create();
699        $this->Tsumego->save($ts);
700        $this->Tsumego->delete($sid);
701
702        $sgfs = $this->Sgf->find('all', ['conditions' => ['tsumego_id' => $t]]);
703        if (!$sgfs) {
704            $sgfs = [];
705        }
706        $sgfsCount = count($sgfs);
707        for ($i = 0; $i < $sgfsCount; $i++) {
708            $sgfs[$i]['Sgf']['tsumego_id'] = $id;
709            $this->Sgf->save($sgfs[$i]);
710        }
711        $x = [];
712        $x['PublishDate']['date'] = $date . ' 22:00:00';
713        $x['PublishDate']['tsumego_id'] = $id;
714        $this->PublishDate->create();
715        $this->PublishDate->save($x);
716
717        return $id;
718    }
719
720    protected function getTsumegoOfTheDay() {
721        $this->loadModel('TsumegoAttempt');
722        $this->loadModel('TsumegoRatingAttempt');
723        $this->loadModel('Schedule');
724        $this->loadModel('Tsumego');
725        $this->loadModel('SetConnection');
726
727        $ut = $this->TsumegoRatingAttempt->find('all', ['limit' => 10000, 'order' => 'created DESC', 'conditions' => ['status' => 'S']]);
728        if (!$ut) {
729            $ut = [];
730        }
731        $out = $this->TsumegoAttempt->find('all', ['limit' => 30000, 'order' => 'created DESC', 'conditions' => ['gain >=' => 40]]);
732        if (!$out) {
733            $out = [];
734        }
735
736        $date = date('Y-m-d', strtotime('yesterday'));
737        $s = $this->Schedule->find('all', ['conditions' => ['date' => $date]]);
738        if (!$s) {
739            $s = [];
740        }
741        $ids = [];
742        $utCount = count($ut);
743        for ($i = 0; $i < $utCount; $i++) {
744            $date2 = new DateTime($ut[$i]['TsumegoRatingAttempt']['created']);
745            $date2 = $date2->format('Y-m-d');
746            if ($date === $date2) {
747                array_push($ids, $ut[$i]['TsumegoRatingAttempt']['tsumego_id']);
748            }
749        }
750        $ids = array_count_values($ids);
751        $highest = 0;
752        $best = [];
753        foreach ($ids as $key => $value) {
754            if ($value > $highest) {
755                $highest = $value;
756            }
757        }
758        foreach ($ids as $key => $value) {
759            if ($value == $highest) {
760                $x = [];
761                $x[$key] = $value;
762                array_push($best, $x);
763            }
764        }
765        $ids2 = [];
766        $out2 = [];
767        $outCount = count($out);
768        for ($i = 0; $i < $outCount; $i++) {
769            $date2 = new DateTime($out[$i]['TsumegoAttempt']['created']);
770            $date2 = $date2->format('Y-m-d');
771            if ($date === $date2) {
772                array_push($ids2, $out[$i]['TsumegoAttempt']['tsumego_id']);
773                array_push($out2, $out[$i]);
774            }
775        }
776        $ids2 = array_count_values($ids2);
777        $highest = 0;
778        $best2 = [];
779        foreach ($ids2 as $key => $value) {
780            if ($value > $highest) {
781                $highest = $value;
782            }
783        }
784        $done = false;
785        $found = 0;
786        $decrement = 0;
787        $best3 = [];
788        $findNum = 20;
789        while (!$done) {
790            foreach ($ids2 as $key => $value) {
791                if ($value == $highest - $decrement) {
792                    array_push($best2, $key);
793                    array_push($best3, $value);
794                    $found++;
795                }
796            }
797            $decrement++;
798            if ($found < $findNum) {
799                $done = false;
800            } else {
801                $done = true;
802            }
803        }
804        $newBest = [];
805        for ($j = 0; $j < $findNum; $j++) {
806            $newBest[$j] = [];
807        }
808        $out2Count = count($out2);
809        for ($i = 0; $i < $out2Count; $i++) {
810            for ($j = 0; $j < $findNum; $j++) {
811                if ($out2[$i]['TsumegoAttempt']['tsumego_id'] == $best2[$j]) {
812                    $x = [];
813                    $x['tid'] = $out2[$i]['TsumegoAttempt']['tsumego_id'];
814                    $tx = $this->Tsumego->findById($x['tid']);
815                    $scT = $this->SetConnection->find('first', ['conditions' => ['tsumego_id' => $tx['Tsumego']['id']]]);
816                    $tx['Tsumego']['set_id'] = $scT['SetConnection']['set_id'];
817                    $x['sid'] = $tx['Tsumego']['set_id'];
818                    $x['status'] = $out2[$i]['TsumegoAttempt']['solved'];
819                    $x['seconds'] = $out2[$i]['TsumegoAttempt']['seconds'];
820
821                    $newBest[$j][] = $x;
822                }
823            }
824        }
825        $newBestCount = count($newBest);
826        for ($i = 0; $i < $newBestCount; $i++) {
827            $sum = 0;
828            $newBestICount = count($newBest[$i]);
829            for ($j = 0; $j < $newBestICount; $j++) {
830                if ($newBest[$i][$j]['seconds'] != null) {
831                    if ($newBest[$i][$j]['seconds'] > 300) {
832                        $newBest[$i][$j]['seconds'] = 300;
833                    }
834                    $sum += $newBest[$i][$j]['seconds'];
835                }
836            }
837            $sum = $sum * count($newBest[$i]);
838            $newBest[$i]['sum'] = $sum;
839        }
840        $highest = 0;
841        $hid = 0;
842        $newBestCount = count($newBest);
843        for ($i = 0; $i < $newBestCount; $i++) {
844            if ($newBest[$i]['sum'] > $highest && $newBest[$i][0]['sid'] != 104 && $newBest[$i][0]['sid'] != 105 && $newBest[$i][0]['sid'] != 117) {
845                $yesterday = false;
846                $sCount = count($s);
847                for ($j = 0; $j < $sCount; $j++) {
848                    if ($newBest[$i][0]['tid'] == $s[$j]['Schedule']['tsumego_id']) {
849                        $yesterday = true;
850                    }
851                }
852                if (!$yesterday) {
853                    $highest = $newBest[$i]['sum'];
854                    $hid = $i;
855                }
856            }
857        }
858
859        return $newBest[$hid][0]['tid'];
860    }
861
862    protected function ratingMatch($elo) {
863        if ($elo >= 3000) {
864            $td = 10;//10d
865        } elseif ($elo >= 2900) {
866            $td = 10;//9d
867        } elseif ($elo >= 2800) {
868            $td = 10;//8d
869        } elseif ($elo >= 2700) {
870            $td = 10;//7d x2700
871        } elseif ($elo >= 2600) {
872            $td = 9;//6d x2600
873        } elseif ($elo >= 2500) {
874            $td = 8;//5d x2500
875        } elseif ($elo >= 2400) {
876            $td = 7;//4d
877        } elseif ($elo >= 2300) {
878            $td = 7;//3d x2350
879        } elseif ($elo >= 2200) {
880            $td = 6;//2d
881        } elseif ($elo >= 2100) {
882            $td = 6;//1d x2150
883        } elseif ($elo >= 2000) {
884            $td = 5;//1k
885        } elseif ($elo >= 1900) {
886            $td = 5;//2k x1950
887        } elseif ($elo >= 1800) {
888            $td = 4;//3k
889        } elseif ($elo >= 1700) {
890            $td = 4;//4k x1750
891        } elseif ($elo >= 1600) {
892            $td = 3;//5k
893        } elseif ($elo >= 1500) {
894            $td = 3;//6k x1500
895        } elseif ($elo >= 1400) {
896            $td = 3;//7k
897        } elseif ($elo >= 1300) {
898            $td = 2;//8k
899        } elseif ($elo >= 1200) {
900            $td = 2;//9k x1200
901        } elseif ($elo >= 1100) {
902            $td = 2;//10k
903        } elseif ($elo >= 1000) {
904            $td = 1;//11k
905        } elseif ($elo >= 900) {
906            $td = 1;//12k x900
907        } elseif ($elo >= 800) {
908            $td = 1;//13k
909        } elseif ($elo >= 700) {
910            $td = 1;//14k
911        } elseif ($elo >= 600) {
912            $td = 1;//15k
913        } elseif ($elo >= 500) {
914            $td = 1;//16k
915        } elseif ($elo >= 400) {
916            $td = 1;//17k
917        } elseif ($elo >= 300) {
918            $td = 1;//18k
919        } elseif ($elo >= 200) {
920            $td = 1;//19k
921        } elseif ($elo >= 100) {
922            $td = 1;//20k
923        } else {
924            $td = 1;
925        }
926
927        return $td;
928    }
929
930    protected function rating2($d) {
931        if ($d == 10) {
932            $elo = 2700;
933        } elseif ($d == 9) {
934            $elo = 2600;
935        } elseif ($d == 8) {
936            $elo = 2500;
937        } elseif ($d == 7) {
938            $elo = 2350;
939        } elseif ($d == 6) {
940            $elo = 2150;
941        } elseif ($d == 5) {
942            $elo = 1950;
943        } elseif ($d == 4) {
944            $elo = 1750;
945        } elseif ($d == 3) {
946            $elo = 1500;
947        } elseif ($d == 2) {
948            $elo = 1200;
949        } elseif ($d == 1) {
950            $elo = 900;
951        } else {
952            $elo = 1500;
953        }
954
955        return $elo;
956    }
957
958    public static function encrypt($str = null) {
959        $secret_key = 'my_simple_secret_keyx';
960        $secret_iv = 'my_simple_secret_ivx';
961        $encrypt_method = 'AES-256-CBC';
962        $key = hash('sha256', $secret_key);
963        $iv = substr(hash('sha256', $secret_iv), 0, 16);
964
965        return base64_encode(openssl_encrypt($str, $encrypt_method, $key, 0, $iv));
966    }
967
968    public static function decrypt($str = null) {
969        $string = $str;
970        $secret_key = 'my_simple_secret_keyx';
971        $secret_iv = 'my_simple_secret_ivx';
972        $encrypt_method = 'AES-256-CBC';
973        $key = hash('sha256', $secret_key);
974        $iv = substr(hash('sha256', $secret_iv), 0, 16);
975
976        return openssl_decrypt(base64_decode($string), $encrypt_method, $key, 0, $iv);
977    }
978
979    protected function checkPictureLarge($u) {
980        if (substr($u['User']['name'], 0, 3) == 'g__' && $u['User']['external_id'] != null) {
981            return '<img class="google-profile-image-large" src="/img/google/' . $u['User']['picture'] . '">' . substr($u['User']['name'], 3);
982        }
983
984        return $u['User']['name'];
985    }
986    public static function checkPicture($user) {
987        if (substr($user['name'], 0, 3) == 'g__' && $user['external_id'] != null) {
988            return '<img class="google-profile-image" src="/img/google/' . $user['picture'] . '">' . substr($user['name'], 3);
989        }
990
991        return $user['name'];
992    }
993
994    public static function getTsumegoRankx($t) {
995        if ($t <= 0) {
996            return '15k';
997        }
998        if ($t > 0 && $t <= 22) {
999            $tRank = '5d';
1000        } elseif ($t <= 26.5) {
1001            $tRank = '4d';
1002        } elseif ($t <= 30) {
1003            $tRank = '3d';
1004        } elseif ($t <= 34) {
1005            $tRank = '2d';
1006        } elseif ($t <= 38) {
1007            $tRank = '1d';
1008        } elseif ($t <= 42) {
1009            $tRank = '1k';
1010        } elseif ($t <= 46) {
1011            $tRank = '2k';
1012        } elseif ($t <= 50) {
1013            $tRank = '3k';
1014        } elseif ($t <= 54.5) {
1015            $tRank = '4k';
1016        } elseif ($t <= 58.5) {
1017            $tRank = '5k';
1018        } elseif ($t <= 63) {
1019            $tRank = '6k';
1020        } elseif ($t <= 67) {
1021            $tRank = '7k';
1022        } elseif ($t <= 70.8) {
1023            $tRank = '8k';
1024        } elseif ($t <= 74.8) {
1025            $tRank = '9k';
1026        } elseif ($t <= 79) {
1027            $tRank = '10k';
1028        } elseif ($t <= 83.5) {
1029            $tRank = '11k';
1030        } elseif ($t <= 88) {
1031            $tRank = '12k';
1032        } elseif ($t <= 92) {
1033            $tRank = '13k';
1034        } elseif ($t <= 96) {
1035            $tRank = '14k';
1036        } else {
1037            $tRank = '15k';
1038        }
1039
1040        return $tRank;
1041    }
1042    protected function adjustElo($v) {
1043        $add = 0;
1044        if ($v >= 1700) {
1045            $add = 110;
1046        } elseif ($v >= 1600) {
1047            $add = 110;
1048        } elseif ($v >= 1700) {
1049            $add = 100;
1050        } elseif ($v >= 1600) {
1051            $add = 90;
1052        } elseif ($v >= 1500) {
1053            $add = 80;
1054        } elseif ($v >= 1400) {
1055            $add = 70;
1056        } elseif ($v >= 1300) {
1057            $add = 60;
1058        } elseif ($v >= 1200) {
1059            $add = 60;
1060        } elseif ($v >= 1100) {
1061            $add = 50;
1062        } elseif ($v >= 1000) {
1063            $add = 50;
1064        } else {
1065            $add = 0;
1066        }
1067
1068        return $v + $add;
1069    }
1070
1071    public static function getTsumegoElo($rank, $p = null) {
1072        if ($p != null) {
1073            $p *= 100;
1074        } else {
1075            $p = 0;
1076        }
1077        $elo = 600;
1078        if ($rank == '9d') {
1079            $elo = round(2900 + $p);
1080        } elseif ($rank == '8d') {
1081            $elo = round(2800 + $p);
1082        } elseif ($rank == '7d') {
1083            $elo = round(2700 + $p);
1084        } elseif ($rank == '6d') {
1085            $elo = round(2600 + $p);
1086        } elseif ($rank == '5d') {
1087            $elo = round(2500 + $p);
1088        } elseif ($rank == '4d') {
1089            $elo = round(2400 + $p);
1090        } elseif ($rank == '3d') {
1091            $elo = round(2300 + $p);
1092        } elseif ($rank == '2d') {
1093            $elo = round(2200 + $p);
1094        } elseif ($rank == '1d') {
1095            $elo = round(2100 + $p);
1096        } elseif ($rank == '1k') {
1097            $elo = round(2000 + $p);
1098        } elseif ($rank == '2k') {
1099            $elo = round(1900 + $p);
1100        } elseif ($rank == '3k') {
1101            $elo = round(1800 + $p);
1102        } elseif ($rank == '4k') {
1103            $elo = round(1700 + $p);
1104        } elseif ($rank == '5k') {
1105            $elo = round(1600 + $p);
1106        } elseif ($rank == '6k') {
1107            $elo = round(1500 + $p);
1108        } elseif ($rank == '7k') {
1109            $elo = round(1400 + $p);
1110        } elseif ($rank == '8k') {
1111            $elo = round(1300 + $p);
1112        } elseif ($rank == '9k') {
1113            $elo = round(1200 + $p);
1114        } elseif ($rank == '10k') {
1115            $elo = round(1100 + $p);
1116        } elseif ($rank == '11k') {
1117            $elo = round(1000 + $p);
1118        } elseif ($rank == '12k') {
1119            $elo = round(900 + $p);
1120        } elseif ($rank == '13k') {
1121            $elo = round(800 + $p);
1122        } elseif ($rank == '14k') {
1123            $elo = round(700 + $p);
1124        } elseif ($rank == '15k' || $rank == '16k' || $rank == '17k' || $rank == '18k' || $rank == '19k' || $rank == '20k' || $rank == '21k') {
1125            $elo = round(600 + $p);
1126        }
1127
1128        return $elo;
1129    }
1130    protected function getTsumegoRankVal($t) {
1131        if ($t <= 0) {
1132            return 0;
1133        }
1134        if ($t > 0 && $t <= 22) {
1135            return 22 - $t;
1136        }
1137        if ($t <= 26.5) {
1138            return 26.5 - $t;
1139        }
1140        if ($t <= 30) {
1141            return 30 - $t;
1142        }
1143        if ($t <= 34) {
1144            return 34 - $t;
1145        }
1146        if ($t <= 38) {
1147            return 38 - $t;
1148        }
1149        if ($t <= 42) {
1150            return 42 - $t;
1151        }
1152        if ($t <= 46) {
1153            return 46 - $t;
1154        }
1155        if ($t <= 50) {
1156            return 50 - $t;
1157        }
1158        if ($t <= 54.5) {
1159            return 54.5 - $t;
1160        }
1161        if ($t <= 58.5) {
1162            return 58.5 - $t;
1163        }
1164        if ($t <= 63) {
1165            return 63 - $t;
1166        }
1167        if ($t <= 67) {
1168            return 67 - $t;
1169        }
1170        if ($t <= 70.8) {
1171            return 70.8 - $t;
1172        }
1173        if ($t <= 74.8) {
1174            return 74.8 - $t;
1175        }
1176        if ($t <= 79) {
1177            return 79 - $t;
1178        }
1179        if ($t <= 83.5) {
1180            return 83.5 - $t;
1181        }
1182        if ($t <= 88) {
1183            return 88 - $t;
1184        }
1185        if ($t <= 92) {
1186            return 92 - $t;
1187        }
1188        if ($t <= 96) {
1189            return 96 - $t;
1190        }
1191
1192        return 100 - $t;
1193    }
1194    protected function getTsumegoRankMax($t) {
1195        if ($t <= 0) {
1196            return 100 - 96;
1197        }
1198        if ($t > 0 && $t <= 22) {
1199            return 22;
1200        }
1201        if ($t <= 26.5) {
1202            return 26.5 - 22;
1203        }
1204        if ($t <= 30) {
1205            return 30 - 26.5;
1206        }
1207        if ($t <= 34) {
1208            return 34 - 30;
1209        }
1210        if ($t <= 38) {
1211            return 38 - 34;
1212        }
1213        if ($t <= 42) {
1214            return 42 - 38;
1215        }
1216        if ($t <= 46) {
1217            return 46 - 42;
1218        }
1219        if ($t <= 50) {
1220            return 50 - 46;
1221        }
1222        if ($t <= 54.5) {
1223            return 54.5 - 50;
1224        }
1225        if ($t <= 58.5) {
1226            return 58.5 - 54.5;
1227        }
1228        if ($t <= 63) {
1229            return 63 - 58.5;
1230        }
1231        if ($t <= 67) {
1232            return 67 - 63;
1233        }
1234        if ($t <= 70.8) {
1235            return 70.8 - 67;
1236        }
1237        if ($t <= 74.8) {
1238            return 74.8 - 70.8;
1239        }
1240        if ($t <= 79) {
1241            return 79 - 74.8;
1242        }
1243        if ($t <= 83.5) {
1244            return 83.5 - 79;
1245        }
1246        if ($t <= 88) {
1247            return 88 - 83.5;
1248        }
1249        if ($t <= 92) {
1250            return 92 - 88;
1251        }
1252        if ($t <= 96) {
1253            return 96 - 92;
1254        }
1255
1256        return 100 - 96;
1257    }
1258
1259    public static function saveDanSolveCondition($solvedTsumegoRank, $tId): void {
1260        if ($solvedTsumegoRank == '1d' || $solvedTsumegoRank == '2d' || $solvedTsumegoRank == '3d' || $solvedTsumegoRank == '4d' || $solvedTsumegoRank == '5d') {
1261            $danSolveCategory = 'danSolve' . $solvedTsumegoRank;
1262            $danSolveCondition = ClassRegistry::init('AchievementCondition')->find('first', [
1263                'order' => 'value DESC',
1264                'conditions' => [
1265                    'user_id' => Auth::getUserID(),
1266                    'category' => $danSolveCategory,
1267                ],
1268            ]);
1269            if (!$danSolveCondition) {
1270                $danSolveCondition = [];
1271                $danSolveCondition['AchievementCondition']['value'] = 0;
1272                ClassRegistry::init('AchievementCondition')->create();
1273            }
1274            $danSolveCondition['AchievementCondition']['category'] = $danSolveCategory;
1275            $danSolveCondition['AchievementCondition']['user_id'] = Auth::getUserID();
1276            $danSolveCondition['AchievementCondition']['set_id'] = $tId;
1277            $danSolveCondition['AchievementCondition']['value']++;
1278
1279            ClassRegistry::init('AchievementCondition')->save($danSolveCondition);
1280        }
1281    }
1282
1283    public static function updateSprintCondition(bool $trigger = false): void {
1284        if (Auth::isLoggedIn()) {
1285            $sprintCondition = ClassRegistry::init('AchievementCondition')->find('first', [
1286                'order' => 'value DESC',
1287                'conditions' => [
1288                    'user_id' => Auth::getUserID(),
1289                    'category' => 'sprint',
1290                ],
1291            ]);
1292            if (!$sprintCondition) {
1293                $sprintCondition = [];
1294                $sprintCondition['AchievementCondition']['value'] = 0;
1295                ClassRegistry::init('AchievementCondition')->create();
1296            }
1297            $sprintCondition['AchievementCondition']['category'] = 'sprint';
1298            $sprintCondition['AchievementCondition']['user_id'] = Auth::getUserID();
1299            if ($trigger) {
1300                $sprintCondition['AchievementCondition']['value']++;
1301            } else {
1302                $sprintCondition['AchievementCondition']['value'] = 0;
1303            }
1304            ClassRegistry::init('AchievementCondition')->save($sprintCondition);
1305        }
1306    }
1307
1308    public static function updateGoldenCondition(bool $trigger = false): void {
1309        $goldenCondition = ClassRegistry::init('AchievementCondition')->find('first', [
1310            'order' => 'value DESC',
1311            'conditions' => [
1312                'user_id' => Auth::getUserID(),
1313                'category' => 'golden',
1314            ],
1315        ]);
1316        if (!$goldenCondition) {
1317            $goldenCondition = [];
1318            $goldenCondition['AchievementCondition']['value'] = 0;
1319            ClassRegistry::init('AchievementCondition')->create();
1320        }
1321        $goldenCondition['AchievementCondition']['category'] = 'golden';
1322        $goldenCondition['AchievementCondition']['user_id'] = Auth::getUserID();
1323        if ($trigger) {
1324            $goldenCondition['AchievementCondition']['value']++;
1325        } else {
1326            $goldenCondition['AchievementCondition']['value'] = 0;
1327        }
1328        ClassRegistry::init('AchievementCondition')->save($goldenCondition);
1329    }
1330
1331    public static function setPotionCondition(): void {
1332        $potionCondition = ClassRegistry::init('AchievementCondition')->find('first', [
1333            'order' => 'value DESC',
1334            'conditions' => [
1335                'user_id' => Auth::getUserID(),
1336                'category' => 'potion',
1337            ],
1338        ]);
1339        if (!$potionCondition) {
1340            $potionCondition = [];
1341            ClassRegistry::init('AchievementCondition')->create();
1342        }
1343        $potionCondition['AchievementCondition']['category'] = 'potion';
1344        $potionCondition['AchievementCondition']['user_id'] = Auth::getUserID();
1345        $potionCondition['AchievementCondition']['value'] = 1;
1346        ClassRegistry::init('AchievementCondition')->save($potionCondition);
1347    }
1348
1349    public static function updateGems(string $rank): void {
1350        $datex = new DateTime('today');
1351        $dateGem = ClassRegistry::init('DayRecord')->find('first', ['conditions' => ['date' => $datex->format('Y-m-d')]]);
1352        if ($dateGem != null) {
1353            $gems = explode('-', $dateGem['DayRecord']['gems']);
1354            $gemValue = '';
1355            $gemValue2 = '';
1356            $gemValue3 = '';
1357            $condition1 = 500;
1358            $condition2 = 200;
1359            $condition3 = 5;
1360            $found1 = false;
1361            $found2 = false;
1362            $found3 = false;
1363            if ($rank == '15k' || $rank == '14k' || $rank == '13k' || $rank == '12k' || $rank == '11k' || $rank == '10k') {
1364                if ($gems[0] == 0) {
1365                    $gemValue = '15k';
1366                } elseif ($gems[0] == 1) {
1367                    $gemValue = '12k';
1368                } elseif ($gems[0] == 2) {
1369                    $gemValue = '10k';
1370                }
1371                if ($rank == $gemValue) {
1372                    $dateGem['DayRecord']['gemCounter1']++;
1373                    if ($dateGem['DayRecord']['gemCounter1'] == $condition1) {
1374                        $found1 = true;
1375                    }
1376                }
1377            } elseif ($rank == '9k' || $rank == '8k' || $rank == '7k' || $rank == '6k' || $rank == '5k' || $rank == '4k' || $rank == '3k' || $rank == '2k' || $rank == '1k') {
1378                if ($gems[1] == 0) {
1379                    $gemValue = '9k';
1380                    $gemValue2 = 'x';
1381                    $gemValue3 = 'y';
1382                } elseif ($gems[1] == 1) {
1383                    $gemValue = '6k';
1384                    $gemValue2 = '5k';
1385                    $gemValue3 = '4k';
1386                } elseif ($gems[1] == 2) {
1387                    $gemValue = 'x';
1388                    $gemValue2 = '2k';
1389                    $gemValue3 = '1k';
1390                }
1391                if ($rank == $gemValue || $rank == $gemValue2 || $rank == $gemValue3) {
1392                    $dateGem['DayRecord']['gemCounter2']++;
1393                    if ($dateGem['DayRecord']['gemCounter2'] == $condition2) {
1394                        $found2 = true;
1395                    }
1396                }
1397            } elseif ($rank == '1d' || $rank == '2d' || $rank == '3d' || $rank == '4d' || $rank == '5d' || $rank == '6d' || $rank == '7d') {
1398                if ($gems[2] == 0) {
1399                    $gemValue = '1d';
1400                    $gemValue2 = '2d';
1401                    $gemValue3 = '3d';
1402                } elseif ($gems[2] == 1) {
1403                    $gemValue = '2d';
1404                    $gemValue2 = '3d';
1405                    $gemValue3 = '4d';
1406                } elseif ($gems[2] == 2) {
1407                    $gemValue = '5d';
1408                    $gemValue2 = '6d';
1409                    $gemValue3 = '7d';
1410                }
1411                if ($rank == $gemValue || $rank == $gemValue2 || $rank == $gemValue3) {
1412                    $dateGem['DayRecord']['gemCounter3']++;
1413                    if ($dateGem['DayRecord']['gemCounter3'] == $condition3) {
1414                        $found3 = true;
1415                    }
1416                }
1417            }
1418            if ($found1) {
1419                $aCondition = ClassRegistry::init('AchievementCondition')->find('first', [
1420                    'order' => 'value DESC',
1421                    'conditions' => [
1422                        'user_id' => Auth::getUserID(),
1423                        'category' => 'emerald',
1424                    ],
1425                ]);
1426                if ($aCondition == null) {
1427                    $aCondition = [];
1428                    $aCondition['AchievementCondition']['category'] = 'emerald';
1429                    $aCondition['AchievementCondition']['user_id'] = Auth::getUserID();
1430                    $aCondition['AchievementCondition']['value'] = 1;
1431                    ClassRegistry::init('AchievementCondition')->save($aCondition);
1432                } else {
1433                    $dateGem['DayRecord']['gemCounter1']--;
1434                }
1435            } elseif ($found2) {
1436                $aCondition = ClassRegistry::init('AchievementCondition')->find('first', [
1437                    'order' => 'value DESC',
1438                    'conditions' => [
1439                        'user_id' => Auth::getUserID(),
1440                        'category' => 'sapphire',
1441                    ],
1442                ]);
1443                if ($aCondition == null) {
1444                    $aCondition = [];
1445                    $aCondition['AchievementCondition']['category'] = 'sapphire';
1446                    $aCondition['AchievementCondition']['user_id'] = Auth::getUserID();
1447                    $aCondition['AchievementCondition']['value'] = 1;
1448                    ClassRegistry::init('AchievementCondition')->save($aCondition);
1449                } else {
1450                    $dateGem['DayRecord']['gemCounter2']--;
1451                }
1452            } elseif ($found3) {
1453                $aCondition = ClassRegistry::init('AchievementCondition')->find('first', [
1454                    'order' => 'value DESC',
1455                    'conditions' => [
1456                        'user_id' => Auth::getUserID(),
1457                        'category' => 'ruby',
1458                    ],
1459                ]);
1460                if ($aCondition == null) {
1461                    $aCondition = [];
1462                    $aCondition['AchievementCondition']['category'] = 'ruby';
1463                    $aCondition['AchievementCondition']['user_id'] = Auth::getUserID();
1464                    $aCondition['AchievementCondition']['value'] = 1;
1465                    ClassRegistry::init('AchievementCondition')->save($aCondition);
1466                } else {
1467                    $dateGem['DayRecord']['gemCounter3']--;
1468                }
1469            }
1470        }
1471        ClassRegistry::init('DayRecord')->save($dateGem);
1472    }
1473
1474    public static function checkProblemNumberAchievements() {
1475        if (!Auth::isLoggedIn()) {
1476            return;
1477        }
1478
1479        $buffer = ClassRegistry::init('AchievementStatus')->find('all', ['conditions' => ['user_id' => Auth::getUserID()]]);
1480        if (!$buffer) {
1481            $buffer = [];
1482        }
1483        $existingAs = [];
1484        $bufferCount = count($buffer);
1485        for ($i = 0; $i < $bufferCount; $i++) {
1486            $existingAs[$buffer[$i]['AchievementStatus']['achievement_id']] = $buffer[$i];
1487        }
1488        $as = [];
1489        $as['AchievementStatus']['user_id'] = Auth::getUserID();
1490        $updated = [];
1491
1492        $achievementId = 1;
1493        $solvedCount = Auth::getUser()['solved'];
1494        if ($solvedCount >= 1000 && !isset($existingAs[$achievementId])) {
1495            $as['AchievementStatus']['achievement_id'] = $achievementId;
1496            ClassRegistry::init('AchievementStatus')->create();
1497            ClassRegistry::init('AchievementStatus')->save($as);
1498            array_push($updated, $achievementId);
1499        }
1500        $achievementId = 2;
1501        if ($solvedCount >= 2000 && !isset($existingAs[$achievementId])) {
1502            $as['AchievementStatus']['achievement_id'] = $achievementId;
1503            ClassRegistry::init('AchievementStatus')->create();
1504            ClassRegistry::init('AchievementStatus')->save($as);
1505            array_push($updated, $achievementId);
1506        }
1507        $achievementId = 3;
1508        if ($solvedCount >= 3000 && !isset($existingAs[$achievementId])) {
1509            $as['AchievementStatus']['achievement_id'] = $achievementId;
1510            ClassRegistry::init('AchievementStatus')->create();
1511            ClassRegistry::init('AchievementStatus')->save($as);
1512            array_push($updated, $achievementId);
1513        }
1514        $achievementId = 4;
1515        if ($solvedCount >= 4000 && !isset($existingAs[$achievementId])) {
1516            $as['AchievementStatus']['achievement_id'] = $achievementId;
1517            ClassRegistry::init('AchievementStatus')->create();
1518            ClassRegistry::init('AchievementStatus')->save($as);
1519            array_push($updated, $achievementId);
1520        }
1521        $achievementId = 5;
1522        if ($solvedCount >= 5000 && !isset($existingAs[$achievementId])) {
1523            $as['AchievementStatus']['achievement_id'] = $achievementId;
1524            ClassRegistry::init('AchievementStatus')->create();
1525            ClassRegistry::init('AchievementStatus')->save($as);
1526            array_push($updated, $achievementId);
1527        }
1528        $achievementId = 6;
1529        if ($solvedCount >= 6000 && !isset($existingAs[$achievementId])) {
1530            $as['AchievementStatus']['achievement_id'] = $achievementId;
1531            ClassRegistry::init('AchievementStatus')->create();
1532            ClassRegistry::init('AchievementStatus')->save($as);
1533            array_push($updated, $achievementId);
1534        }
1535        $achievementId = 7;
1536        if ($solvedCount >= 7000 && !isset($existingAs[$achievementId])) {
1537            $as['AchievementStatus']['achievement_id'] = $achievementId;
1538            ClassRegistry::init('AchievementStatus')->create();
1539            ClassRegistry::init('AchievementStatus')->save($as);
1540            array_push($updated, $achievementId);
1541        }
1542        $achievementId = 8;
1543        if ($solvedCount >= 8000 && !isset($existingAs[$achievementId])) {
1544            $as['AchievementStatus']['achievement_id'] = $achievementId;
1545            ClassRegistry::init('AchievementStatus')->create();
1546            ClassRegistry::init('AchievementStatus')->save($as);
1547            array_push($updated, $achievementId);
1548        }
1549        $achievementId = 9;
1550        if ($solvedCount >= 9000 && !isset($existingAs[$achievementId])) {
1551            $as['AchievementStatus']['achievement_id'] = $achievementId;
1552            ClassRegistry::init('AchievementStatus')->create();
1553            ClassRegistry::init('AchievementStatus')->save($as);
1554            array_push($updated, $achievementId);
1555        }
1556        $achievementId = 10;
1557        if ($solvedCount >= 10000 && !isset($existingAs[$achievementId])) {
1558            $as['AchievementStatus']['achievement_id'] = $achievementId;
1559            ClassRegistry::init('AchievementStatus')->create();
1560            ClassRegistry::init('AchievementStatus')->save($as);
1561            array_push($updated, $achievementId);
1562        }
1563        //uotd achievement
1564        $achievementId = 11;
1565        if (!isset($existingAs[$achievementId])) {
1566            $condition = ClassRegistry::init('AchievementCondition')->find('first', ['conditions' => ['user_id' => Auth::getUserID(), 'category' => 'uotd']]);
1567            if ($condition != null) {
1568                $as['AchievementStatus']['achievement_id'] = $achievementId;
1569                ClassRegistry::init('AchievementStatus')->create();
1570                ClassRegistry::init('AchievementStatus')->save($as);
1571                array_push($updated, $achievementId);
1572            }
1573        }
1574
1575        $updatedCount = count($updated);
1576        for ($i = 0; $i < $updatedCount; $i++) {
1577            $a = ClassRegistry::init('Achievement')->findById($updated[$i]);
1578            $updated[$i] = [];
1579            $updated[$i][0] = $a['Achievement']['name'];
1580            $updated[$i][1] = $a['Achievement']['description'];
1581            $updated[$i][2] = $a['Achievement']['image'];
1582            $updated[$i][3] = $a['Achievement']['color'];
1583            $updated[$i][4] = $a['Achievement']['xp'];
1584            $updated[$i][5] = $a['Achievement']['id'];
1585        }
1586
1587        return $updated;
1588    }
1589
1590    public static function checkDanSolveAchievements() {
1591        if (Auth::isLoggedIn()) {
1592            $buffer = ClassRegistry::init('AchievementStatus')->find('all', ['conditions' => ['user_id' => Auth::getUserID()]]);
1593            if (!$buffer) {
1594                $buffer = [];
1595            }
1596            $ac = ClassRegistry::init('AchievementCondition')->find('all', [
1597                'order' => 'category ASC',
1598                'conditions' => [
1599                    'user_id' => Auth::getUserID(),
1600                    'OR' => [
1601                        ['category' => 'danSolve1d'],
1602                        ['category' => 'danSolve2d'],
1603                        ['category' => 'danSolve3d'],
1604                        ['category' => 'danSolve4d'],
1605                        ['category' => 'danSolve5d'],
1606                        ['category' => 'emerald'],
1607                        ['category' => 'sapphire'],
1608                        ['category' => 'ruby'],
1609                        ['category' => 'sprint'],
1610                        ['category' => 'golden'],
1611                        ['category' => 'potion'],
1612                    ],
1613                ],
1614            ]);
1615            if (!$ac) {
1616                $ac = [];
1617            }
1618            $ac1 = [];
1619            $acCount = count($ac);
1620            for ($i = 0; $i < $acCount; $i++) {
1621                if ($ac[$i]['AchievementCondition']['category'] == 'danSolve1d') {
1622                    $ac1['1d'] = $ac[$i]['AchievementCondition']['value'];
1623                } elseif ($ac[$i]['AchievementCondition']['category'] == 'danSolve2d') {
1624                    $ac1['2d'] = $ac[$i]['AchievementCondition']['value'];
1625                } elseif ($ac[$i]['AchievementCondition']['category'] == 'danSolve3d') {
1626                    $ac1['3d'] = $ac[$i]['AchievementCondition']['value'];
1627                } elseif ($ac[$i]['AchievementCondition']['category'] == 'danSolve4d') {
1628                    $ac1['4d'] = $ac[$i]['AchievementCondition']['value'];
1629                } elseif ($ac[$i]['AchievementCondition']['category'] == 'danSolve5d') {
1630                    $ac1['5d'] = $ac[$i]['AchievementCondition']['value'];
1631                } elseif ($ac[$i]['AchievementCondition']['category'] == 'emerald') {
1632                    $ac1['emerald'] = $ac[$i]['AchievementCondition']['value'];
1633                } elseif ($ac[$i]['AchievementCondition']['category'] == 'sapphire') {
1634                    $ac1['sapphire'] = $ac[$i]['AchievementCondition']['value'];
1635                } elseif ($ac[$i]['AchievementCondition']['category'] == 'ruby') {
1636                    $ac1['ruby'] = $ac[$i]['AchievementCondition']['value'];
1637                } elseif ($ac[$i]['AchievementCondition']['category'] == 'sprint') {
1638                    $ac1['sprint'] = $ac[$i]['AchievementCondition']['value'];
1639                } elseif ($ac[$i]['AchievementCondition']['category'] == 'golden') {
1640                    $ac1['golden'] = $ac[$i]['AchievementCondition']['value'];
1641                } elseif ($ac[$i]['AchievementCondition']['category'] == 'potion') {
1642                    $ac1['potion'] = $ac[$i]['AchievementCondition']['value'];
1643                }
1644            }
1645
1646            $existingAs = [];
1647            $bufferCount = count($buffer);
1648            for ($i = 0; $i < $bufferCount; $i++) {
1649                $existingAs[$buffer[$i]['AchievementStatus']['achievement_id']] = $buffer[$i];
1650            }
1651            $as = [];
1652            $as['AchievementStatus']['user_id'] = Auth::getUserID();
1653            $updated = [];
1654            $achievementId = 101;
1655            if ($ac1['1d'] > 0 && !isset($existingAs[$achievementId])) {
1656                $as['AchievementStatus']['achievement_id'] = $achievementId;
1657                ClassRegistry::init('AchievementStatus')->create();
1658                ClassRegistry::init('AchievementStatus')->save($as);
1659                array_push($updated, $achievementId);
1660            }
1661            $achievementId = 102;
1662            if ($ac1['2d'] > 0 && !isset($existingAs[$achievementId])) {
1663                $as['AchievementStatus']['achievement_id'] = $achievementId;
1664                ClassRegistry::init('AchievementStatus')->create();
1665                ClassRegistry::init('AchievementStatus')->save($as);
1666                array_push($updated, $achievementId);
1667            }
1668            $achievementId = 103;
1669            if ($ac1['3d'] > 0 && !isset($existingAs[$achievementId])) {
1670                $as['AchievementStatus']['achievement_id'] = $achievementId;
1671                ClassRegistry::init('AchievementStatus')->create();
1672                ClassRegistry::init('AchievementStatus')->save($as);
1673                array_push($updated, $achievementId);
1674            }
1675            $achievementId = 104;
1676            if ($ac1['4d'] > 0 && !isset($existingAs[$achievementId])) {
1677                $as['AchievementStatus']['achievement_id'] = $achievementId;
1678                ClassRegistry::init('AchievementStatus')->create();
1679                ClassRegistry::init('AchievementStatus')->save($as);
1680                array_push($updated, $achievementId);
1681            }
1682            $achievementId = 105;
1683            if ($ac1['5d'] > 0 && !isset($existingAs[$achievementId])) {
1684                $as['AchievementStatus']['achievement_id'] = $achievementId;
1685                ClassRegistry::init('AchievementStatus')->create();
1686                ClassRegistry::init('AchievementStatus')->save($as);
1687                array_push($updated, $achievementId);
1688            }
1689            $achievementId = 106;
1690            if ($ac1['1d'] >= 10 && !isset($existingAs[$achievementId])) {
1691                $as['AchievementStatus']['achievement_id'] = $achievementId;
1692                ClassRegistry::init('AchievementStatus')->create();
1693                ClassRegistry::init('AchievementStatus')->save($as);
1694                array_push($updated, $achievementId);
1695            }
1696            $achievementId = 107;
1697            if ($ac1['2d'] >= 10 && !isset($existingAs[$achievementId])) {
1698                $as['AchievementStatus']['achievement_id'] = $achievementId;
1699                ClassRegistry::init('AchievementStatus')->create();
1700                ClassRegistry::init('AchievementStatus')->save($as);
1701                array_push($updated, $achievementId);
1702            }
1703            $achievementId = 108;
1704            if ($ac1['3d'] >= 10 && !isset($existingAs[$achievementId])) {
1705                $as['AchievementStatus']['achievement_id'] = $achievementId;
1706                ClassRegistry::init('AchievementStatus')->create();
1707                ClassRegistry::init('AchievementStatus')->save($as);
1708                array_push($updated, $achievementId);
1709            }
1710            $achievementId = 109;
1711            if ($ac1['4d'] >= 10 && !isset($existingAs[$achievementId])) {
1712                $as['AchievementStatus']['achievement_id'] = $achievementId;
1713                ClassRegistry::init('AchievementStatus')->create();
1714                ClassRegistry::init('AchievementStatus')->save($as);
1715                array_push($updated, $achievementId);
1716            }
1717            $achievementId = 110;
1718            if ($ac1['5d'] >= 10 && !isset($existingAs[$achievementId])) {
1719                $as['AchievementStatus']['achievement_id'] = $achievementId;
1720                ClassRegistry::init('AchievementStatus')->create();
1721                ClassRegistry::init('AchievementStatus')->save($as);
1722                array_push($updated, $achievementId);
1723            }
1724            $achievementId = 111;
1725            if (isset($ac1['emerald'])) {
1726                if ($ac1['emerald'] == 1 && !isset($existingAs[$achievementId])) {
1727                    $as['AchievementStatus']['achievement_id'] = $achievementId;
1728                    ClassRegistry::init('AchievementStatus')->create();
1729                    ClassRegistry::init('AchievementStatus')->save($as);
1730                    array_push($updated, $achievementId);
1731                }
1732            }
1733            $achievementId = 112;
1734            if (isset($ac1['sapphire'])) {
1735                if ($ac1['sapphire'] == 1 && !isset($existingAs[$achievementId])) {
1736                    $as['AchievementStatus']['achievement_id'] = $achievementId;
1737                    ClassRegistry::init('AchievementStatus')->create();
1738                    ClassRegistry::init('AchievementStatus')->save($as);
1739                    array_push($updated, $achievementId);
1740                }
1741            }
1742            $achievementId = 113;
1743            if (isset($ac1['ruby'])) {
1744                if ($ac1['ruby'] == 1 && !isset($existingAs[$achievementId])) {
1745                    $as['AchievementStatus']['achievement_id'] = $achievementId;
1746                    ClassRegistry::init('AchievementStatus')->create();
1747                    ClassRegistry::init('AchievementStatus')->save($as);
1748                    array_push($updated, $achievementId);
1749                }
1750            }
1751            $achievementId = 114;
1752            if (!isset($existingAs[$achievementId]) && isset($existingAs[111]) && isset($existingAs[112]) && isset($existingAs[113])) {
1753                $as['AchievementStatus']['achievement_id'] = $achievementId;
1754                ClassRegistry::init('AchievementStatus')->create();
1755                ClassRegistry::init('AchievementStatus')->save($as);
1756                array_push($updated, $achievementId);
1757            }
1758            $achievementId = 96;
1759            if (!isset($existingAs[$achievementId]) && $ac1['sprint'] >= 30) {
1760                $as['AchievementStatus']['achievement_id'] = $achievementId;
1761                ClassRegistry::init('AchievementStatus')->create();
1762                ClassRegistry::init('AchievementStatus')->save($as);
1763                array_push($updated, $achievementId);
1764            }
1765            $achievementId = 97;
1766            if (!isset($existingAs[$achievementId]) && $ac1['golden'] >= 10) {
1767                $as['AchievementStatus']['achievement_id'] = $achievementId;
1768                ClassRegistry::init('AchievementStatus')->create();
1769                ClassRegistry::init('AchievementStatus')->save($as);
1770                array_push($updated, $achievementId);
1771            }
1772            $achievementId = 98;
1773            if (!isset($existingAs[$achievementId]) && $ac1['potion'] >= 1) {
1774                $as['AchievementStatus']['achievement_id'] = $achievementId;
1775                ClassRegistry::init('AchievementStatus')->create();
1776                ClassRegistry::init('AchievementStatus')->save($as);
1777                array_push($updated, $achievementId);
1778            }
1779            $updatedCount = count($updated);
1780            for ($i = 0; $i < $updatedCount; $i++) {
1781                $a = ClassRegistry::init('Achievement')->findById($updated[$i]);
1782                $updated[$i] = [];
1783                $updated[$i][0] = $a['Achievement']['name'];
1784                $updated[$i][1] = $a['Achievement']['description'];
1785                $updated[$i][2] = $a['Achievement']['image'];
1786                $updated[$i][3] = $a['Achievement']['color'];
1787                $updated[$i][4] = $a['Achievement']['xp'];
1788                $updated[$i][5] = $a['Achievement']['id'];
1789            }
1790
1791            return $updated;
1792        }
1793    }
1794
1795    protected function checkForLocked($t, $setsWithPremium) {
1796        $scCheck = $this->SetConnection->find('first', ['conditions' => ['tsumego_id' => $t['Tsumego']['id']]]);
1797        if ($scCheck && in_array($scCheck['SetConnection']['set_id'], $setsWithPremium) && !Auth::hasPremium()) {
1798            $t['Tsumego']['locked'] = true;
1799        } else {
1800            $t['Tsumego']['locked'] = false;
1801        }
1802
1803        return $t;
1804    }
1805    public static function checkNoErrorAchievements() {
1806        if (Auth::isLoggedIn()) {
1807
1808            $ac = ClassRegistry::init('AchievementCondition')->find('first', [
1809                'order' => 'value DESC',
1810                'conditions' => [
1811                    'user_id' => Auth::getUserID(),
1812                    'category' => 'err',
1813                ],
1814            ]);
1815
1816            $buffer = ClassRegistry::init('AchievementStatus')->find('all', ['conditions' => ['user_id' => Auth::getUserID()]]);
1817            if (!$buffer) {
1818                $buffer = [];
1819            }
1820            $existingAs = [];
1821            $bufferCount = count($buffer);
1822            for ($i = 0; $i < $bufferCount; $i++) {
1823                $existingAs[$buffer[$i]['AchievementStatus']['achievement_id']] = $buffer[$i];
1824            }
1825            $as = [];
1826            $as['AchievementStatus']['user_id'] = Auth::getUserID();
1827            $updated = [];
1828
1829            $achievementId = 53;
1830            if ($ac['AchievementCondition']['value'] >= 10 && !isset($existingAs[$achievementId])) {
1831                $as['AchievementStatus']['achievement_id'] = $achievementId;
1832                ClassRegistry::init('AchievementStatus')->create();
1833                ClassRegistry::init('AchievementStatus')->save($as);
1834                array_push($updated, $achievementId);
1835            }
1836            $achievementId = 54;
1837            if ($ac['AchievementCondition']['value'] >= 20 && !isset($existingAs[$achievementId])) {
1838                $as['AchievementStatus']['achievement_id'] = $achievementId;
1839                ClassRegistry::init('AchievementStatus')->create();
1840                ClassRegistry::init('AchievementStatus')->save($as);
1841                array_push($updated, $achievementId);
1842            }
1843            $achievementId = 55;
1844            if ($ac['AchievementCondition']['value'] >= 30 && !isset($existingAs[$achievementId])) {
1845                $as['AchievementStatus']['achievement_id'] = $achievementId;
1846                ClassRegistry::init('AchievementStatus')->create();
1847                ClassRegistry::init('AchievementStatus')->save($as);
1848                array_push($updated, $achievementId);
1849            }
1850            $achievementId = 56;
1851            if ($ac['AchievementCondition']['value'] >= 50 && !isset($existingAs[$achievementId])) {
1852                $as['AchievementStatus']['achievement_id'] = $achievementId;
1853                ClassRegistry::init('AchievementStatus')->create();
1854                ClassRegistry::init('AchievementStatus')->save($as);
1855                array_push($updated, $achievementId);
1856            }
1857            $achievementId = 57;
1858            if ($ac['AchievementCondition']['value'] >= 100 && !isset($existingAs[$achievementId])) {
1859                $as['AchievementStatus']['achievement_id'] = $achievementId;
1860                ClassRegistry::init('AchievementStatus')->create();
1861                ClassRegistry::init('AchievementStatus')->save($as);
1862                array_push($updated, $achievementId);
1863            }
1864            $achievementId = 58;
1865            if ($ac['AchievementCondition']['value'] >= 200 && !isset($existingAs[$achievementId])) {
1866                $as['AchievementStatus']['achievement_id'] = $achievementId;
1867                ClassRegistry::init('AchievementStatus')->create();
1868                ClassRegistry::init('AchievementStatus')->save($as);
1869                array_push($updated, $achievementId);
1870            }
1871            $updatedCount = count($updated);
1872            for ($i = 0; $i < $updatedCount; $i++) {
1873                $a = ClassRegistry::init('Achievement')->findById($updated[$i]);
1874                $updated[$i] = [];
1875                $updated[$i][0] = $a['Achievement']['name'];
1876                $updated[$i][1] = $a['Achievement']['description'];
1877                $updated[$i][2] = $a['Achievement']['image'];
1878                $updated[$i][3] = $a['Achievement']['color'];
1879                $updated[$i][4] = $a['Achievement']['xp'];
1880                $updated[$i][5] = $a['Achievement']['id'];
1881            }
1882
1883            return $updated;
1884        }
1885    }
1886
1887    protected function checkTimeModeAchievements() {
1888        $this->loadModel('Achievement');
1889        $this->loadModel('AchievementStatus');
1890        $this->loadModel('TimeModeSession');
1891
1892        $buffer = ClassRegistry::init('AchievementStatus')->find('all', ['conditions' => ['user_id' => Auth::getUserID()]]);
1893        if (!$buffer) {
1894            $buffer = [];
1895        }
1896        $existingAs = [];
1897        $bufferCount = count($buffer);
1898        for ($i = 0; $i < $bufferCount; $i++) {
1899            $existingAs[$buffer[$i]['AchievementStatus']['achievement_id']] = $buffer[$i];
1900        }
1901        $as = [];
1902        $as['AchievementStatus']['user_id'] = Auth::getUserID();
1903        $updated = [];
1904
1905        $rBlitz = $this->TimeModeSession->find('all', ['conditions' => ['time_mode_category_id' => TimeModeUtil::$CATEGORY_BLITZ, 'user_id' => Auth::getUserID()]]);
1906        if (!$rBlitz) {
1907            $rBlitz = [];
1908        }
1909        $rFast = $this->TimeModeSession->find('all', ['conditions' => ['time_mode_category_id' => TimeModeUtil::$CATEGORY_FAST_SPEED, 'user_id' => Auth::getUserID()]]);
1910        if (!$rFast) {
1911            $rFast = [];
1912        }
1913        $rSlow = $this->TimeModeSession->find('all', ['conditions' => ['time_mode_category_id' => TimeModeUtil::$CATEGORY_SLOW_SPEED, 'user_id' => Auth::getUserID()]]);
1914        if (!$rSlow) {
1915            $rSlow = [];
1916        }
1917        $r = $this->TimeModeSession->find('all', ['conditions' => ['user_id' => Auth::getUserID()]]);
1918        if (!$r) {
1919            $r = [];
1920        }
1921
1922        $timeModeAchievements = [];
1923        for ($i = 70; $i <= 91; $i++) {
1924            $timeModeAchievements[$i] = false;
1925        }
1926        $rCount = count($r);
1927        for ($i = 0; $i < $rCount; $i++) {
1928            if ($r[$i]['TimeModeSession']['status'] == 's') {
1929                if ($r[$i]['TimeModeSession']['TimeModeAttempt'] == '5k') {
1930                    if ($r[$i]['TimeModeSession']['mode'] == 2) {
1931                        $timeModeAchievements[70] = true;
1932                    } elseif ($r[$i]['TimeModeSession']['mode'] == 1) {
1933                        $timeModeAchievements[76] = true;
1934                    } elseif ($r[$i]['TimeModeSession']['mode'] == 0) {
1935                        $timeModeAchievements[82] = true;
1936                    }
1937                } elseif ($r[$i]['TimeModeSession']['TimeModeAttempt'] == '4k') {
1938                    if ($r[$i]['TimeModeSession']['mode'] == 2) {
1939                        $timeModeAchievements[71] = true;
1940                    } elseif ($r[$i]['TimeModeSession']['mode'] == 1) {
1941                        $timeModeAchievements[77] = true;
1942                    } elseif ($r[$i]['TimeModeSession']['mode'] == 0) {
1943                        $timeModeAchievements[83] = true;
1944                    }
1945                } elseif ($r[$i]['TimeModeSession']['TimeModeAttempt'] == '3k') {
1946                    if ($r[$i]['TimeModeSession']['mode'] == 2) {
1947                        $timeModeAchievements[72] = true;
1948                    } elseif ($r[$i]['TimeModeSession']['mode'] == 1) {
1949                        $timeModeAchievements[78] = true;
1950                    } elseif ($r[$i]['TimeModeSession']['mode'] == 0) {
1951                        $timeModeAchievements[84] = true;
1952                    }
1953                } elseif ($r[$i]['TimeModeSession']['TimeModeAttempt'] == '2k') {
1954                    if ($r[$i]['TimeModeSession']['mode'] == 2) {
1955                        $timeModeAchievements[73] = true;
1956                    } elseif ($r[$i]['TimeModeSession']['mode'] == 1) {
1957                        $timeModeAchievements[79] = true;
1958                    } elseif ($r[$i]['TimeModeSession']['mode'] == 0) {
1959                        $timeModeAchievements[85] = true;
1960                    }
1961                } elseif ($r[$i]['TimeModeSession']['TimeModeAttempt'] == '1k') {
1962                    if ($r[$i]['TimeModeSession']['mode'] == 2) {
1963                        $timeModeAchievements[74] = true;
1964                    } elseif ($r[$i]['TimeModeSession']['mode'] == 1) {
1965                        $timeModeAchievements[80] = true;
1966                    } elseif ($r[$i]['TimeModeSession']['mode'] == 0) {
1967                        $timeModeAchievements[86] = true;
1968                    }
1969                } elseif ($r[$i]['TimeModeSession']['TimeModeAttempt'] == '1d') {
1970                    if ($r[$i]['TimeModeSession']['mode'] == 2) {
1971                        $timeModeAchievements[75] = true;
1972                    } elseif ($r[$i]['TimeModeSession']['mode'] == 1) {
1973                        $timeModeAchievements[81] = true;
1974                    } elseif ($r[$i]['TimeModeSession']['mode'] == 0) {
1975                        $timeModeAchievements[87] = true;
1976                    }
1977                }
1978            }
1979            if ($r[$i]['TimeModeSession']['points'] >= 850
1980            && ($r[$i]['TimeModeSession']['TimeModeAttempt'] == '4k' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '3k' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '2k' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '1k'
1981            || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '1d' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '2d' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '3d' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '4d'
1982            || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '5d')) {
1983                $timeModeAchievements[91] = true;
1984            }
1985            if ($r[$i]['TimeModeSession']['points'] >= 875
1986            && ($r[$i]['TimeModeSession']['TimeModeAttempt'] == '4k' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '3k' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '2k' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '1k'
1987            || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '1d' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '2d' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '3d' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '4d'
1988            || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '5d' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '5k' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '6k')) {
1989                $timeModeAchievements[90] = true;
1990            }
1991            if ($r[$i]['TimeModeSession']['points'] >= 900
1992            && ($r[$i]['TimeModeSession']['TimeModeAttempt'] == '4k' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '3k' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '2k' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '1k'
1993            || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '1d' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '2d' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '3d' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '4d'
1994            || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '5d' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '5k' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '6k' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '7k'
1995            || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '8k')) {
1996                $timeModeAchievements[89] = true;
1997            }
1998            if ($r[$i]['TimeModeSession']['points'] >= 950
1999            && ($r[$i]['TimeModeSession']['TimeModeAttempt'] == '4k' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '3k' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '2k' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '1k'
2000            || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '1d' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '2d' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '3d' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '4d'
2001            || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '5d' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '5k' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '6k' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '7k'
2002            || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '8k' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '9k' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '10k')) {
2003                $timeModeAchievements[88] = true;
2004            }
2005        }
2006        for ($i = 70; $i <= 91; $i++) {
2007            $achievementId = $i;
2008            if ($timeModeAchievements[$achievementId] == true && !isset($existingAs[$achievementId])) {
2009                $as['AchievementStatus']['achievement_id'] = $achievementId;
2010                ClassRegistry::init('AchievementStatus')->create();
2011                ClassRegistry::init('AchievementStatus')->save($as);
2012                array_push($updated, $achievementId);
2013            }
2014        }
2015        $updatedCount = count($updated);
2016        for ($i = 0; $i < $updatedCount; $i++) {
2017            $a = ClassRegistry::init('Achievement')->findById($updated[$i]);
2018            $updated[$i] = [];
2019            $updated[$i][0] = $a['Achievement']['name'];
2020            $updated[$i][1] = $a['Achievement']['description'];
2021            $updated[$i][2] = $a['Achievement']['image'];
2022            $updated[$i][3] = $a['Achievement']['color'];
2023            $updated[$i][4] = $a['Achievement']['xp'];
2024            $updated[$i][5] = $a['Achievement']['id'];
2025        }
2026
2027        return $updated;
2028    }
2029
2030    public static function checkRatingAchievements() {
2031        if (!Auth::isLoggedIn()) {
2032            return;
2033        }
2034
2035        $buffer = ClassRegistry::init('AchievementStatus')->find('all', ['conditions' => ['user_id' => Auth::getUserID()]]);
2036        if (!$buffer) {
2037            $buffer = [];
2038        }
2039        $existingAs = [];
2040        $bufferCount = count($buffer);
2041        for ($i = 0; $i < $bufferCount; $i++) {
2042            $existingAs[$buffer[$i]['AchievementStatus']['achievement_id']] = $buffer[$i];
2043        }
2044        $as = [];
2045        $as['AchievementStatus']['user_id'] = Auth::getUserID();
2046        $updated = [];
2047
2048        $achievementId = 59;
2049        $currentElo = Auth::getUser()['rating'];
2050        if ($currentElo >= 1500 && !isset($existingAs[$achievementId])) {
2051            $as['AchievementStatus']['achievement_id'] = $achievementId;
2052            ClassRegistry::init('AchievementStatus')->create();
2053            ClassRegistry::init('AchievementStatus')->save($as);
2054            array_push($updated, $achievementId);
2055        }
2056        $achievementId = 60;
2057        if ($currentElo >= 1600 && !isset($existingAs[$achievementId])) {
2058            $as['AchievementStatus']['achievement_id'] = $achievementId;
2059            ClassRegistry::init('AchievementStatus')->create();
2060            ClassRegistry::init('AchievementStatus')->save($as);
2061            array_push($updated, $achievementId);
2062        }
2063        $achievementId = 61;
2064        if ($currentElo >= 1700 && !isset($existingAs[$achievementId])) {
2065            $as['AchievementStatus']['achievement_id'] = $achievementId;
2066            ClassRegistry::init('AchievementStatus')->create();
2067            ClassRegistry::init('AchievementStatus')->save($as);
2068            array_push($updated, $achievementId);
2069        }
2070        $achievementId = 62;
2071        if ($currentElo >= 1800 && !isset($existingAs[$achievementId])) {
2072            $as['AchievementStatus']['achievement_id'] = $achievementId;
2073            ClassRegistry::init('AchievementStatus')->create();
2074            ClassRegistry::init('AchievementStatus')->save($as);
2075            array_push($updated, $achievementId);
2076        }
2077        $achievementId = 63;
2078        if ($currentElo >= 1900 && !isset($existingAs[$achievementId])) {
2079            $as['AchievementStatus']['achievement_id'] = $achievementId;
2080            ClassRegistry::init('AchievementStatus')->create();
2081            ClassRegistry::init('AchievementStatus')->save($as);
2082            array_push($updated, $achievementId);
2083        }
2084        $achievementId = 64;
2085        if ($currentElo >= 2000 && !isset($existingAs[$achievementId])) {
2086            $as['AchievementStatus']['achievement_id'] = $achievementId;
2087            ClassRegistry::init('AchievementStatus')->create();
2088            ClassRegistry::init('AchievementStatus')->save($as);
2089            array_push($updated, $achievementId);
2090        }
2091        $achievementId = 65;
2092        if ($currentElo >= 2100 && !isset($existingAs[$achievementId])) {
2093            $as['AchievementStatus']['achievement_id'] = $achievementId;
2094            ClassRegistry::init('AchievementStatus')->create();
2095            ClassRegistry::init('AchievementStatus')->save($as);
2096            array_push($updated, $achievementId);
2097        }
2098        $achievementId = 66;
2099        if ($currentElo >= 2200 && !isset($existingAs[$achievementId])) {
2100            $as['AchievementStatus']['achievement_id'] = $achievementId;
2101            ClassRegistry::init('AchievementStatus')->create();
2102            ClassRegistry::init('AchievementStatus')->save($as);
2103            array_push($updated, $achievementId);
2104        }
2105        $achievementId = 67;
2106        if ($currentElo >= 2300 && !isset($existingAs[$achievementId])) {
2107            $as['AchievementStatus']['achievement_id'] = $achievementId;
2108            ClassRegistry::init('AchievementStatus')->create();
2109            ClassRegistry::init('AchievementStatus')->save($as);
2110            array_push($updated, $achievementId);
2111        }
2112        $achievementId = 68;
2113        if ($currentElo >= 2400 && !isset($existingAs[$achievementId])) {
2114            $as['AchievementStatus']['achievement_id'] = $achievementId;
2115            ClassRegistry::init('AchievementStatus')->create();
2116            ClassRegistry::init('AchievementStatus')->save($as);
2117            array_push($updated, $achievementId);
2118        }
2119        $achievementId = 69;
2120        if ($currentElo >= 2500 && !isset($existingAs[$achievementId])) {
2121            $as['AchievementStatus']['achievement_id'] = $achievementId;
2122            ClassRegistry::init('AchievementStatus')->create();
2123            ClassRegistry::init('AchievementStatus')->save($as);
2124            array_push($updated, $achievementId);
2125        }
2126        $updatedCount = count($updated);
2127        for ($i = 0; $i < $updatedCount; $i++) {
2128            $a = ClassRegistry::init('Achievement')->findById($updated[$i]);
2129            $updated[$i] = [];
2130            $updated[$i][0] = $a['Achievement']['name'];
2131            $updated[$i][1] = $a['Achievement']['description'];
2132            $updated[$i][2] = $a['Achievement']['image'];
2133            $updated[$i][3] = $a['Achievement']['color'];
2134            $updated[$i][4] = $a['Achievement']['xp'];
2135            $updated[$i][5] = $a['Achievement']['id'];
2136        }
2137
2138        return $updated;
2139    }
2140
2141    public static function checkLevelAchievements() {
2142        if (!Auth::isLoggedIn()) {
2143            return;
2144        }
2145        $buffer = ClassRegistry::init('AchievementStatus')->find('all', ['conditions' => ['user_id' => Auth::getUserID()]]);
2146        if (!$buffer) {
2147            $buffer = [];
2148        }
2149        $existingAs = [];
2150        $bufferCount = count($buffer);
2151        for ($i = 0; $i < $bufferCount; $i++) {
2152            $existingAs[$buffer[$i]['AchievementStatus']['achievement_id']] = $buffer[$i];
2153        }
2154        $as = [];
2155        $as['AchievementStatus']['user_id'] = Auth::getUserID();
2156        $updated = [];
2157
2158        $achievementId = 36;
2159        $userLevel = Auth::getUser()['level'];
2160        if ($userLevel >= 10 && !isset($existingAs[$achievementId])) {
2161            $as['AchievementStatus']['achievement_id'] = $achievementId;
2162            ClassRegistry::init('AchievementStatus')->create();
2163            ClassRegistry::init('AchievementStatus')->save($as);
2164            array_push($updated, $achievementId);
2165        }
2166        $achievementId = 37;
2167        if ($userLevel >= 20 && !isset($existingAs[$achievementId])) {
2168            $as['AchievementStatus']['achievement_id'] = $achievementId;
2169            ClassRegistry::init('AchievementStatus')->create();
2170            ClassRegistry::init('AchievementStatus')->save($as);
2171            array_push($updated, $achievementId);
2172        }
2173        $achievementId = 38;
2174        if ($userLevel >= 30 && !isset($existingAs[$achievementId])) {
2175            $as['AchievementStatus']['achievement_id'] = $achievementId;
2176            ClassRegistry::init('AchievementStatus')->create();
2177            ClassRegistry::init('AchievementStatus')->save($as);
2178            array_push($updated, $achievementId);
2179        }
2180        $achievementId = 39;
2181        if ($userLevel >= 40 && !isset($existingAs[$achievementId])) {
2182            $as['AchievementStatus']['achievement_id'] = $achievementId;
2183            ClassRegistry::init('AchievementStatus')->create();
2184            ClassRegistry::init('AchievementStatus')->save($as);
2185            array_push($updated, $achievementId);
2186        }
2187        $achievementId = 40;
2188        if ($userLevel >= 50 && !isset($existingAs[$achievementId])) {
2189            $as['AchievementStatus']['achievement_id'] = $achievementId;
2190            ClassRegistry::init('AchievementStatus')->create();
2191            ClassRegistry::init('AchievementStatus')->save($as);
2192            array_push($updated, $achievementId);
2193        }
2194        $achievementId = 41;
2195        if ($userLevel >= 60 && !isset($existingAs[$achievementId])) {
2196            $as['AchievementStatus']['achievement_id'] = $achievementId;
2197            ClassRegistry::init('AchievementStatus')->create();
2198            ClassRegistry::init('AchievementStatus')->save($as);
2199            array_push($updated, $achievementId);
2200        }
2201        $achievementId = 42;
2202        if ($userLevel >= 70 && !isset($existingAs[$achievementId])) {
2203            $as['AchievementStatus']['achievement_id'] = $achievementId;
2204            ClassRegistry::init('AchievementStatus')->create();
2205            ClassRegistry::init('AchievementStatus')->save($as);
2206            array_push($updated, $achievementId);
2207        }
2208        $achievementId = 43;
2209        if ($userLevel >= 80 && !isset($existingAs[$achievementId])) {
2210            $as['AchievementStatus']['achievement_id'] = $achievementId;
2211            ClassRegistry::init('AchievementStatus')->create();
2212            ClassRegistry::init('AchievementStatus')->save($as);
2213            array_push($updated, $achievementId);
2214        }
2215        $achievementId = 44;
2216        if ($userLevel >= 90 && !isset($existingAs[$achievementId])) {
2217            $as['AchievementStatus']['achievement_id'] = $achievementId;
2218            ClassRegistry::init('AchievementStatus')->create();
2219            ClassRegistry::init('AchievementStatus')->save($as);
2220            array_push($updated, $achievementId);
2221        }
2222        $achievementId = 45;
2223        if ($userLevel >= 100 && !isset($existingAs[$achievementId])) {
2224            $as['AchievementStatus']['achievement_id'] = $achievementId;
2225            ClassRegistry::init('AchievementStatus')->create();
2226            ClassRegistry::init('AchievementStatus')->save($as);
2227            array_push($updated, $achievementId);
2228        }
2229        $achievementId = 100;
2230        if (Auth::hasPremium() && !isset($existingAs[$achievementId])) {
2231            $as['AchievementStatus']['achievement_id'] = $achievementId;
2232            ClassRegistry::init('AchievementStatus')->create();
2233            ClassRegistry::init('AchievementStatus')->save($as);
2234            array_push($updated, $achievementId);
2235        }
2236        $updatedCount = count($updated);
2237        for ($i = 0; $i < $updatedCount; $i++) {
2238            $a = ClassRegistry::init('Achievement')->findById($updated[$i]);
2239            $updated[$i] = [];
2240            $updated[$i][0] = $a['Achievement']['name'];
2241            $updated[$i][1] = $a['Achievement']['description'];
2242            $updated[$i][2] = $a['Achievement']['image'];
2243            $updated[$i][3] = $a['Achievement']['color'];
2244            $updated[$i][4] = $a['Achievement']['xp'];
2245            $updated[$i][5] = $a['Achievement']['id'];
2246        }
2247
2248        return $updated;
2249    }
2250
2251    protected function checkSetCompletedAchievements() {
2252        $this->loadModel('Set');
2253        $this->loadModel('Tsumego');
2254        $this->loadModel('Achievement');
2255        $this->loadModel('AchievementStatus');
2256        $this->loadModel('AchievementCondition');
2257
2258        $ac = ClassRegistry::init('AchievementCondition')->find('first', [
2259            'order' => 'value DESC',
2260            'conditions' => [
2261                'user_id' => Auth::getUserID(),
2262                'category' => 'set',
2263            ],
2264        ]);
2265
2266        if (!$ac) {
2267            return [];
2268        }
2269
2270        $buffer = ClassRegistry::init('AchievementStatus')->find('all', ['conditions' => ['user_id' => Auth::getUserID()]]);
2271        if (!$buffer) {
2272            $buffer = [];
2273        }
2274        $existingAs = [];
2275        $bufferCount = count($buffer);
2276        for ($i = 0; $i < $bufferCount; $i++) {
2277            $existingAs[$buffer[$i]['AchievementStatus']['achievement_id']] = $buffer[$i];
2278        }
2279        $as = [];
2280        $as['AchievementStatus']['user_id'] = Auth::getUserID();
2281        $updated = [];
2282
2283        $achievementId = 47;
2284        if ($ac['AchievementCondition']['value'] >= 10 && !isset($existingAs[$achievementId])) {
2285            $as['AchievementStatus']['achievement_id'] = $achievementId;
2286            ClassRegistry::init('AchievementStatus')->create();
2287            ClassRegistry::init('AchievementStatus')->save($as);
2288            array_push($updated, $achievementId);
2289        }
2290        $achievementId = 48;
2291        if ($ac['AchievementCondition']['value'] >= 20 && !isset($existingAs[$achievementId])) {
2292            $as['AchievementStatus']['achievement_id'] = $achievementId;
2293            ClassRegistry::init('AchievementStatus')->create();
2294            ClassRegistry::init('AchievementStatus')->save($as);
2295            array_push($updated, $achievementId);
2296        }
2297        $achievementId = 49;
2298        if ($ac['AchievementCondition']['value'] >= 30 && !isset($existingAs[$achievementId])) {
2299            $as['AchievementStatus']['achievement_id'] = $achievementId;
2300            ClassRegistry::init('AchievementStatus')->create();
2301            ClassRegistry::init('AchievementStatus')->save($as);
2302            array_push($updated, $achievementId);
2303        }
2304        $achievementId = 50;
2305        if ($ac['AchievementCondition']['value'] >= 40 && !isset($existingAs[$achievementId])) {
2306            $as['AchievementStatus']['achievement_id'] = $achievementId;
2307            ClassRegistry::init('AchievementStatus')->create();
2308            ClassRegistry::init('AchievementStatus')->save($as);
2309            array_push($updated, $achievementId);
2310        }
2311        $achievementId = 51;
2312        if ($ac['AchievementCondition']['value'] >= 50 && !isset($existingAs[$achievementId])) {
2313            $as['AchievementStatus']['achievement_id'] = $achievementId;
2314            ClassRegistry::init('AchievementStatus')->create();
2315            ClassRegistry::init('AchievementStatus')->save($as);
2316            array_push($updated, $achievementId);
2317        }
2318        $achievementId = 52;
2319        if ($ac['AchievementCondition']['value'] >= 60 && !isset($existingAs[$achievementId])) {
2320            $as['AchievementStatus']['achievement_id'] = $achievementId;
2321            ClassRegistry::init('AchievementStatus')->create();
2322            ClassRegistry::init('AchievementStatus')->save($as);
2323            array_push($updated, $achievementId);
2324        }
2325        $updatedCount = count($updated);
2326        for ($i = 0; $i < $updatedCount; $i++) {
2327            $a = ClassRegistry::init('Achievement')->findById($updated[$i]);
2328            $updated[$i] = [];
2329            $updated[$i][0] = $a['Achievement']['name'];
2330            $updated[$i][1] = $a['Achievement']['description'];
2331            $updated[$i][2] = $a['Achievement']['image'];
2332            $updated[$i][3] = $a['Achievement']['color'];
2333            $updated[$i][4] = $a['Achievement']['xp'];
2334            $updated[$i][5] = $a['Achievement']['id'];
2335        }
2336
2337        return $updated;
2338    }
2339
2340    protected function setAchievementSpecial($s = null) {
2341        $this->loadModel('Set');
2342        $this->loadModel('Tsumego');
2343        $this->loadModel('TsumegoStatus');
2344        $this->loadModel('Achievement');
2345        $this->loadModel('AchievementStatus');
2346        $this->loadModel('SetConnection');
2347
2348        $buffer = ClassRegistry::init('AchievementStatus')->find('all', ['conditions' => ['user_id' => Auth::getUserID()]]);
2349        if (!$buffer) {
2350            $buffer = [];
2351        }
2352        $existingAs = [];
2353        $bufferCount = count($buffer);
2354        for ($i = 0; $i < $bufferCount; $i++) {
2355            $existingAs[$buffer[$i]['AchievementStatus']['achievement_id']] = $buffer[$i];
2356        }
2357        $as = [];
2358        $as['AchievementStatus']['user_id'] = Auth::getUserID();
2359        $updated = [];
2360
2361        $tsIds = [];
2362        $completed = '';
2363        if ($s == 'cc1') {
2364            $ts1 = TsumegoUtil::collectTsumegosFromSet(50);
2365            $ts2 = TsumegoUtil::collectTsumegosFromSet(52);
2366            $ts3 = TsumegoUtil::collectTsumegosFromSet(53);
2367            $ts4 = TsumegoUtil::collectTsumegosFromSet(54);
2368            $ts = array_merge($ts1, $ts2, $ts3, $ts4);
2369            $tsCount = count($ts);
2370            for ($i = 0; $i < $tsCount; $i++) {
2371                array_push($tsIds, $ts[$i]['Tsumego']['id']);
2372            }
2373            $uts = $this->TsumegoStatus->find('all', [
2374                'conditions' => [
2375                    'user_id' => Auth::getUserID(),
2376                    'tsumego_id' => $tsIds,
2377                ],
2378            ]);
2379            if (!$uts) {
2380                $uts = [];
2381            }
2382            $counter = 0;
2383            $utsCount = count($uts);
2384            for ($j = 0; $j < $utsCount; $j++) {
2385                for ($k = 0; $k < $tsCount; $k++) {
2386                    if ($uts[$j]['TsumegoStatus']['tsumego_id'] == $ts[$k]['Tsumego']['id'] && ($uts[$j]['TsumegoStatus']['status'] == 'S'
2387                    || $uts[$j]['TsumegoStatus']['status'] == 'W' || $uts[$j]['TsumegoStatus']['status'] == 'C')) {
2388                        $counter++;
2389                    }
2390                }
2391            }
2392            if ($counter == count($ts)) {
2393                $completed = $s;
2394            }
2395        } elseif ($s == 'cc2') {
2396            $ts1 = TsumegoUtil::collectTsumegosFromSet(41);
2397            $ts2 = TsumegoUtil::collectTsumegosFromSet(49);
2398            $ts3 = TsumegoUtil::collectTsumegosFromSet(65);
2399            $ts4 = TsumegoUtil::collectTsumegosFromSet(66);
2400            $ts = array_merge($ts1, $ts2, $ts3, $ts4);
2401            $tsCount = count($ts);
2402            for ($i = 0; $i < $tsCount; $i++) {
2403                array_push($tsIds, $ts[$i]['Tsumego']['id']);
2404            }
2405            $uts = $this->TsumegoStatus->find('all', [
2406                'conditions' => [
2407                    'user_id' => Auth::getUserID(),
2408                    'tsumego_id' => $tsIds,
2409                ],
2410            ]);
2411            if (!$uts) {
2412                $uts = [];
2413            }
2414            $counter = 0;
2415            $utsCount = count($uts);
2416            for ($j = 0; $j < $utsCount; $j++) {
2417                for ($k = 0; $k < $tsCount; $k++) {
2418                    if ($uts[$j]['TsumegoStatus']['tsumego_id'] == $ts[$k]['Tsumego']['id'] && ($uts[$j]['TsumegoStatus']['status'] == 'S'
2419                    || $uts[$j]['TsumegoStatus']['status'] == 'W' || $uts[$j]['TsumegoStatus']['status'] == 'C')) {
2420                        $counter++;
2421                    }
2422                }
2423            }
2424            if ($counter == count($ts)) {
2425                $completed = $s;
2426            }
2427        } elseif ($s == 'cc3') {
2428            $ts1 = TsumegoUtil::collectTsumegosFromSet(186);
2429            $ts2 = TsumegoUtil::collectTsumegosFromSet(187);
2430            $ts3 = TsumegoUtil::collectTsumegosFromSet(196);
2431            $ts4 = TsumegoUtil::collectTsumegosFromSet(203);
2432            $ts = array_merge($ts1, $ts2, $ts3, $ts4);
2433            $tsCount = count($ts);
2434            for ($i = 0; $i < $tsCount; $i++) {
2435                array_push($tsIds, $ts[$i]['Tsumego']['id']);
2436            }
2437            $uts = $this->TsumegoStatus->find('all', [
2438                'conditions' => [
2439                    'user_id' => Auth::getUserID(),
2440                    'tsumego_id' => $tsIds,
2441                ],
2442            ]);
2443            if (!$uts) {
2444                $uts = [];
2445            }
2446            $counter = 0;
2447            $utsCount = count($uts);
2448            for ($j = 0; $j < $utsCount; $j++) {
2449                for ($k = 0; $k < $tsCount; $k++) {
2450                    if ($uts[$j]['TsumegoStatus']['tsumego_id'] == $ts[$k]['Tsumego']['id'] && ($uts[$j]['TsumegoStatus']['status'] == 'S'
2451                    || $uts[$j]['TsumegoStatus']['status'] == 'W' || $uts[$j]['TsumegoStatus']['status'] == 'C')) {
2452                        $counter++;
2453                    }
2454                }
2455            }
2456            if ($counter == count($ts)) {
2457                $completed = $s;
2458            }
2459        } elseif ($s == '1000w1') {
2460            $ts1 = TsumegoUtil::collectTsumegosFromSet(190);
2461            $ts2 = TsumegoUtil::collectTsumegosFromSet(193);
2462            $ts3 = TsumegoUtil::collectTsumegosFromSet(198);
2463            $ts = array_merge($ts1, $ts2, $ts3);
2464            $tsCount = count($ts);
2465            for ($i = 0; $i < $tsCount; $i++) {
2466                array_push($tsIds, $ts[$i]['Tsumego']['id']);
2467            }
2468            $uts = $this->TsumegoStatus->find('all', [
2469                'conditions' => [
2470                    'user_id' => Auth::getUserID(),
2471                    'tsumego_id' => $tsIds,
2472                ],
2473            ]);
2474            if (!$uts) {
2475                $uts = [];
2476            }
2477            $counter = 0;
2478            $utsCount = count($uts);
2479            for ($j = 0; $j < $utsCount; $j++) {
2480                for ($k = 0; $k < $tsCount; $k++) {
2481                    if ($uts[$j]['TsumegoStatus']['tsumego_id'] == $ts[$k]['Tsumego']['id'] && ($uts[$j]['TsumegoStatus']['status'] == 'S'
2482                    || $uts[$j]['TsumegoStatus']['status'] == 'W' || $uts[$j]['TsumegoStatus']['status'] == 'C')) {
2483                        $counter++;
2484                    }
2485                }
2486            }
2487            if ($counter == count($ts)) {
2488                $completed = $s;
2489            }
2490        } elseif ($s == '1000w2') {
2491            $ts = TsumegoUtil::collectTsumegosFromSet(216);
2492            $tsCount = count($ts);
2493            for ($i = 0; $i < $tsCount; $i++) {
2494                array_push($tsIds, $ts[$i]['Tsumego']['id']);
2495            }
2496            $uts = $this->TsumegoStatus->find('all', [
2497                'conditions' => [
2498                    'user_id' => Auth::getUserID(),
2499                    'tsumego_id' => $tsIds,
2500                ],
2501            ]);
2502            if (!$uts) {
2503                $uts = [];
2504            }
2505            $counter = 0;
2506            $utsCount = count($uts);
2507            for ($j = 0; $j < $utsCount; $j++) {
2508                for ($k = 0; $k < $tsCount; $k++) {
2509                    if ($uts[$j]['TsumegoStatus']['tsumego_id'] == $ts[$k]['Tsumego']['id'] && ($uts[$j]['TsumegoStatus']['status'] == 'S'
2510                    || $uts[$j]['TsumegoStatus']['status'] == 'W' || $uts[$j]['TsumegoStatus']['status'] == 'C')) {
2511                        $counter++;
2512                    }
2513                }
2514            }
2515            if ($counter == count($ts)) {
2516                $completed = $s;
2517            }
2518        }
2519
2520        $achievementId = 92;
2521        if ($completed == 'cc1' && !isset($existingAs[$achievementId])) {
2522            $as['AchievementStatus']['achievement_id'] = $achievementId;
2523            ClassRegistry::init('AchievementStatus')->create();
2524            ClassRegistry::init('AchievementStatus')->save($as);
2525            array_push($updated, $achievementId);
2526        }
2527        $achievementId = 93;
2528        if ($completed == 'cc2' && !isset($existingAs[$achievementId])) {
2529            $as['AchievementStatus']['achievement_id'] = $achievementId;
2530            ClassRegistry::init('AchievementStatus')->create();
2531            ClassRegistry::init('AchievementStatus')->save($as);
2532            array_push($updated, $achievementId);
2533        }
2534        $achievementId = 94;
2535        if ($completed == 'cc3' && !isset($existingAs[$achievementId])) {
2536            $as['AchievementStatus']['achievement_id'] = $achievementId;
2537            ClassRegistry::init('AchievementStatus')->create();
2538            ClassRegistry::init('AchievementStatus')->save($as);
2539            array_push($updated, $achievementId);
2540        }
2541        $achievementId = 95;
2542        if ($completed == '1000w1' && !isset($existingAs[$achievementId])) {
2543            $as['AchievementStatus']['achievement_id'] = $achievementId;
2544            ClassRegistry::init('AchievementStatus')->create();
2545            ClassRegistry::init('AchievementStatus')->save($as);
2546            array_push($updated, $achievementId);
2547        }
2548        $achievementId = 115;
2549        if ($completed == '1000w2' && !isset($existingAs[$achievementId])) {
2550            $as['AchievementStatus']['achievement_id'] = $achievementId;
2551            ClassRegistry::init('AchievementStatus')->create();
2552            ClassRegistry::init('AchievementStatus')->save($as);
2553            array_push($updated, $achievementId);
2554        }
2555        $updatedCount = count($updated);
2556        for ($i = 0; $i < $updatedCount; $i++) {
2557            $a = ClassRegistry::init('Achievement')->findById($updated[$i]);
2558            $updated[$i] = [];
2559            $updated[$i][0] = $a['Achievement']['name'];
2560            $updated[$i][1] = $a['Achievement']['description'];
2561            $updated[$i][2] = $a['Achievement']['image'];
2562            $updated[$i][3] = $a['Achievement']['color'];
2563            $updated[$i][4] = $a['Achievement']['xp'];
2564            $updated[$i][5] = $a['Achievement']['id'];
2565        }
2566
2567        return $updated;
2568    }
2569
2570    protected function checkSetAchievements($sid = null) {
2571        $this->loadModel('Set');
2572        $this->loadModel('Tsumego');
2573        $this->loadModel('Achievement');
2574        $this->loadModel('AchievementStatus');
2575        $this->loadModel('AchievementCondition');
2576
2577        //$tNum = count($this->Tsumego->find('all', array('conditions' => array('set_id' => $sid))));
2578        $tNum = count(TsumegoUtil::collectTsumegosFromSet($sid));
2579        $s = $this->Set->findById($sid);
2580        $acA = ClassRegistry::init('AchievementCondition')->find('first', [
2581            'order' => 'value DESC',
2582            'conditions' => [
2583                'set_id' => $sid,
2584                'user_id' => Auth::getUserID(),
2585                'category' => '%',
2586            ],
2587        ]);
2588        if (!$acA) {
2589            return [];
2590        }
2591        $acS = ClassRegistry::init('AchievementCondition')->find('first', [
2592            'order' => 'value ASC',
2593            'conditions' => [
2594                'set_id' => $sid,
2595                'user_id' => Auth::getUserID(),
2596                'category' => 's',
2597            ],
2598        ]);
2599        $buffer = ClassRegistry::init('AchievementStatus')->find('all', ['conditions' => ['user_id' => Auth::getUserID()]]);
2600        if (!$buffer) {
2601            $buffer = [];
2602        }
2603        $existingAs = [];
2604        $bufferCount = count($buffer);
2605        for ($i = 0; $i < $bufferCount; $i++) {
2606            $existingAs[$buffer[$i]['AchievementStatus']['achievement_id']] = $buffer[$i];
2607        }
2608        $as = [];
2609        $as['AchievementStatus']['user_id'] = Auth::getUserID();
2610        $updated = [];
2611
2612        $achievementId = 99;
2613        if ($sid == -1 && !isset($existingAs[$achievementId])) {
2614            $as['AchievementStatus']['achievement_id'] = $achievementId;
2615            ClassRegistry::init('AchievementStatus')->create();
2616            ClassRegistry::init('AchievementStatus')->save($as);
2617            array_push($updated, $achievementId);
2618        }
2619        if ($tNum >= 100) {
2620            if ($s['Set']['difficulty'] < 1300) {
2621                $achievementId = 12;
2622                if ($acA['AchievementCondition']['value'] >= 75 && !isset($existingAs[$achievementId])) {
2623                    $as['AchievementStatus']['achievement_id'] = $achievementId;
2624                    ClassRegistry::init('AchievementStatus')->create();
2625                    ClassRegistry::init('AchievementStatus')->save($as);
2626                    array_push($updated, $achievementId);
2627                }
2628                $achievementId = 13;
2629                if ($acA['AchievementCondition']['value'] >= 85 && !isset($existingAs[$achievementId])) {
2630                    $as['AchievementStatus']['achievement_id'] = $achievementId;
2631                    ClassRegistry::init('AchievementStatus')->create();
2632                    ClassRegistry::init('AchievementStatus')->save($as);
2633                    array_push($updated, $achievementId);
2634                }
2635                $achievementId = 14;
2636                if ($acA['AchievementCondition']['value'] >= 95 && !isset($existingAs[$achievementId])) {
2637                    $as['AchievementStatus']['achievement_id'] = $achievementId;
2638                    ClassRegistry::init('AchievementStatus')->create();
2639                    ClassRegistry::init('AchievementStatus')->save($as);
2640                    array_push($updated, $achievementId);
2641                }
2642                $achievementId = 24;
2643                if ($acS['AchievementCondition']['value'] < 15 && !isset($existingAs[$achievementId])) {
2644                    $as['AchievementStatus']['achievement_id'] = $achievementId;
2645                    ClassRegistry::init('AchievementStatus')->create();
2646                    ClassRegistry::init('AchievementStatus')->save($as);
2647                    array_push($updated, $achievementId);
2648                }
2649                $achievementId = 25;
2650                if ($acS['AchievementCondition']['value'] < 10 && !isset($existingAs[$achievementId])) {
2651                    $as['AchievementStatus']['achievement_id'] = $achievementId;
2652                    ClassRegistry::init('AchievementStatus')->create();
2653                    ClassRegistry::init('AchievementStatus')->save($as);
2654                    array_push($updated, $achievementId);
2655                }
2656                $achievementId = 26;
2657                if ($acS['AchievementCondition']['value'] < 5 && !isset($existingAs[$achievementId])) {
2658                    $as['AchievementStatus']['achievement_id'] = $achievementId;
2659                    ClassRegistry::init('AchievementStatus')->create();
2660                    ClassRegistry::init('AchievementStatus')->save($as);
2661                    array_push($updated, $achievementId);
2662                }
2663            } elseif ($s['Set']['difficulty'] >= 1300 && $s['Set']['difficulty'] < 1500) {
2664                $achievementId = 15;
2665                if ($acA['AchievementCondition']['value'] >= 75 && !isset($existingAs[$achievementId])) {
2666                    $as['AchievementStatus']['achievement_id'] = $achievementId;
2667                    ClassRegistry::init('AchievementStatus')->create();
2668                    ClassRegistry::init('AchievementStatus')->save($as);
2669                    array_push($updated, $achievementId);
2670                }
2671                $achievementId = 16;
2672                if ($acA['AchievementCondition']['value'] >= 85 && !isset($existingAs[$achievementId])) {
2673                    $as['AchievementStatus']['achievement_id'] = $achievementId;
2674                    ClassRegistry::init('AchievementStatus')->create();
2675                    ClassRegistry::init('AchievementStatus')->save($as);
2676                    array_push($updated, $achievementId);
2677                }
2678                $achievementId = 17;
2679                if ($acA['AchievementCondition']['value'] >= 95 && !isset($existingAs[$achievementId])) {
2680                    $as['AchievementStatus']['achievement_id'] = $achievementId;
2681                    ClassRegistry::init('AchievementStatus')->create();
2682                    ClassRegistry::init('AchievementStatus')->save($as);
2683                    array_push($updated, $achievementId);
2684                }
2685                $achievementId = 27;
2686                if ($acS['AchievementCondition']['value'] < 18 && !isset($existingAs[$achievementId])) {
2687                    $as['AchievementStatus']['achievement_id'] = $achievementId;
2688                    ClassRegistry::init('AchievementStatus')->create();
2689                    ClassRegistry::init('AchievementStatus')->save($as);
2690                    array_push($updated, $achievementId);
2691                }
2692                $achievementId = 28;
2693                if ($acS['AchievementCondition']['value'] < 13 && !isset($existingAs[$achievementId])) {
2694                    $as['AchievementStatus']['achievement_id'] = $achievementId;
2695                    ClassRegistry::init('AchievementStatus')->create();
2696                    ClassRegistry::init('AchievementStatus')->save($as);
2697                    array_push($updated, $achievementId);
2698                }
2699                $achievementId = 29;
2700                if ($acS['AchievementCondition']['value'] < 8 && !isset($existingAs[$achievementId])) {
2701                    $as['AchievementStatus']['achievement_id'] = $achievementId;
2702                    ClassRegistry::init('AchievementStatus')->create();
2703                    ClassRegistry::init('AchievementStatus')->save($as);
2704                    array_push($updated, $achievementId);
2705                }
2706            } elseif ($s['Set']['difficulty'] >= 1500 && $s['Set']['difficulty'] < 1700) {
2707                $achievementId = 18;
2708                if ($acA['AchievementCondition']['value'] >= 75 && !isset($existingAs[$achievementId])) {
2709                    $as['AchievementStatus']['achievement_id'] = $achievementId;
2710                    ClassRegistry::init('AchievementStatus')->create();
2711                    ClassRegistry::init('AchievementStatus')->save($as);
2712                    array_push($updated, $achievementId);
2713                }
2714                $achievementId = 19;
2715                if ($acA['AchievementCondition']['value'] >= 85 && !isset($existingAs[$achievementId])) {
2716                    $as['AchievementStatus']['achievement_id'] = $achievementId;
2717                    ClassRegistry::init('AchievementStatus')->create();
2718                    ClassRegistry::init('AchievementStatus')->save($as);
2719                    array_push($updated, $achievementId);
2720                }
2721                $achievementId = 20;
2722                if ($acA['AchievementCondition']['value'] >= 95 && !isset($existingAs[$achievementId])) {
2723                    $as['AchievementStatus']['achievement_id'] = $achievementId;
2724                    ClassRegistry::init('AchievementStatus')->create();
2725                    ClassRegistry::init('AchievementStatus')->save($as);
2726                    array_push($updated, $achievementId);
2727                }
2728                $achievementId = 30;
2729                if ($acS['AchievementCondition']['value'] < 30 && !isset($existingAs[$achievementId])) {
2730                    $as['AchievementStatus']['achievement_id'] = $achievementId;
2731                    ClassRegistry::init('AchievementStatus')->create();
2732                    ClassRegistry::init('AchievementStatus')->save($as);
2733                    array_push($updated, $achievementId);
2734                }
2735                $achievementId = 31;
2736                if ($acS['AchievementCondition']['value'] < 20 && !isset($existingAs[$achievementId])) {
2737                    $as['AchievementStatus']['achievement_id'] = $achievementId;
2738                    ClassRegistry::init('AchievementStatus')->create();
2739                    ClassRegistry::init('AchievementStatus')->save($as);
2740                    array_push($updated, $achievementId);
2741                }
2742                $achievementId = 32;
2743                if ($acS['AchievementCondition']['value'] < 10 && !isset($existingAs[$achievementId])) {
2744                    $as['AchievementStatus']['achievement_id'] = $achievementId;
2745                    ClassRegistry::init('AchievementStatus')->create();
2746                    ClassRegistry::init('AchievementStatus')->save($as);
2747                    array_push($updated, $achievementId);
2748                }
2749            } else {
2750                $achievementId = 21;
2751                if ($acA['AchievementCondition']['value'] >= 75 && !isset($existingAs[$achievementId])) {
2752                    $as['AchievementStatus']['achievement_id'] = $achievementId;
2753                    ClassRegistry::init('AchievementStatus')->create();
2754                    ClassRegistry::init('AchievementStatus')->save($as);
2755                    array_push($updated, $achievementId);
2756                }
2757                $achievementId = 22;
2758                if ($acA['AchievementCondition']['value'] >= 85 && !isset($existingAs[$achievementId])) {
2759                    $as['AchievementStatus']['achievement_id'] = $achievementId;
2760                    ClassRegistry::init('AchievementStatus')->create();
2761                    ClassRegistry::init('AchievementStatus')->save($as);
2762                    array_push($updated, $achievementId);
2763                }
2764                $achievementId = 23;
2765                if ($acA['AchievementCondition']['value'] >= 95 && !isset($existingAs[$achievementId])) {
2766                    $as['AchievementStatus']['achievement_id'] = $achievementId;
2767                    ClassRegistry::init('AchievementStatus')->create();
2768                    ClassRegistry::init('AchievementStatus')->save($as);
2769                    array_push($updated, $achievementId);
2770                }
2771                $achievementId = 33;
2772                if ($acS['AchievementCondition']['value'] < 30 && !isset($existingAs[$achievementId])) {
2773                    $as['AchievementStatus']['achievement_id'] = $achievementId;
2774                    ClassRegistry::init('AchievementStatus')->create();
2775                    ClassRegistry::init('AchievementStatus')->save($as);
2776                    array_push($updated, $achievementId);
2777                }
2778                $achievementId = 34;
2779                if ($acS['AchievementCondition']['value'] < 20 && !isset($existingAs[$achievementId])) {
2780                    $as['AchievementStatus']['achievement_id'] = $achievementId;
2781                    ClassRegistry::init('AchievementStatus')->create();
2782                    ClassRegistry::init('AchievementStatus')->save($as);
2783                    array_push($updated, $achievementId);
2784                }
2785                $achievementId = 35;
2786                if ($acS['AchievementCondition']['value'] < 10 && !isset($existingAs[$achievementId])) {
2787                    $as['AchievementStatus']['achievement_id'] = $achievementId;
2788                    ClassRegistry::init('AchievementStatus')->create();
2789                    ClassRegistry::init('AchievementStatus')->save($as);
2790                    array_push($updated, $achievementId);
2791                }
2792            }
2793            $achievementId = 46;
2794            if ($acA['AchievementCondition']['value'] >= 100) {
2795                $ac100 = ClassRegistry::init('AchievementCondition')->find('all', ['conditions' => ['user_id' => Auth::getUserID(), 'category' => '%', 'value >=' => 100]]);
2796                if (!$ac100) {
2797                    $ac100 = [];
2798                }
2799                $ac100counter = 0;
2800                $ac100Count = count($ac100);
2801                for ($j = 0; $j < $ac100Count; $j++) {
2802                    if (count(TsumegoUtil::collectTsumegosFromSet($ac100[$j]['AchievementCondition']['set_id'])) >= 100) {
2803                        $ac100counter++;
2804                    }
2805                }
2806                $as100 = ClassRegistry::init('AchievementStatus')->find('first', ['conditions' => ['user_id' => Auth::getUserID(), 'achievement_id' => $achievementId]]);
2807                if ($as100 == null) {
2808                    $as['AchievementStatus']['achievement_id'] = $achievementId;
2809                    $as['AchievementStatus']['value'] = 1;
2810                    ClassRegistry::init('AchievementStatus')->create();
2811                    ClassRegistry::init('AchievementStatus')->save($as);
2812                    array_push($updated, $achievementId);
2813                } elseif ($as100['AchievementStatus']['value'] != $ac100counter) {
2814                    $as100['AchievementStatus']['value'] = $ac100counter;
2815                    ClassRegistry::init('AchievementStatus')->save($as100);
2816                    array_push($updated, $achievementId);
2817                }
2818            }
2819        }
2820        $updatedCount = count($updated);
2821        for ($i = 0; $i < $updatedCount; $i++) {
2822            $a = ClassRegistry::init('Achievement')->findById($updated[$i]);
2823            $updated[$i] = [];
2824            $updated[$i][0] = $a['Achievement']['name'];
2825            $updated[$i][1] = $a['Achievement']['description'];
2826            $updated[$i][2] = $a['Achievement']['image'];
2827            $updated[$i][3] = $a['Achievement']['color'];
2828            $updated[$i][4] = $a['Achievement']['xp'];
2829            $updated[$i][5] = $a['Achievement']['id'];
2830        }
2831
2832        return $updated;
2833    }
2834
2835    public static function getXPJump($lvl = null): int {
2836        if ($lvl >= 102) {
2837            return 0;
2838        }
2839        if ($lvl == 101) {
2840            return 1150;
2841        }
2842        if ($lvl == 100) {
2843            return 50000;
2844        }
2845        if ($lvl >= 70) {
2846            return 150;
2847        }
2848        if ($lvl >= 40) {
2849            return 100;
2850        }
2851        if ($lvl >= 20) {
2852            return 50;
2853        }
2854        if ($lvl >= 12) {
2855            return 25;
2856        }
2857
2858        return 10;
2859    }
2860
2861    public static function updateXP($userID, $achievementData): void {
2862        $xpBonus = 0;
2863        $aCount = count($achievementData);
2864        for ($i = 0; $i < $aCount; $i++) {
2865            $xpBonus += $achievementData[$i][4];
2866        }
2867        $u = ClassRegistry::init('User')->findById($userID);
2868        $jumps = [];
2869        $xStart = 40;
2870
2871        for ($i = 1; $i < 102; $i++) {
2872            if ($i == 101) {
2873                $j = 1150;
2874            } elseif ($i == 100) {
2875                $j = 50000;
2876            } elseif ($i >= 70) {
2877                $j = 150;
2878            } elseif ($i >= 40) {
2879                $j = 100;
2880            } elseif ($i >= 20) {
2881                $j = 50;
2882            } elseif ($i >= 12) {
2883                $j = 25;
2884            } else {
2885                $j = 10;
2886            }
2887            $xStart += $j;
2888            $jumps[$i] = $xStart;
2889        }
2890        $next = 0;
2891        $uLevel = $u['User']['level'];
2892        $uXp = $u['User']['xp'];
2893
2894        if ($uLevel < 101) {
2895            $currentJump = $jumps[$uLevel];
2896        } else {
2897            $currentJump = 60000;
2898        }
2899
2900        $firstJump = $currentJump;
2901
2902        if ($uXp + $xpBonus >= $currentJump) {
2903            $next = $uXp + $xpBonus - $currentJump;
2904            $uLevel++;
2905            if ($uLevel < 101) {
2906                $currentJump = $jumps[$uLevel];
2907            } else {
2908                $currentJump = 60000;
2909            }
2910        }
2911        while ($next >= $currentJump) {
2912            $next = $next - $currentJump;
2913            $uLevel++;
2914            if ($uLevel < 101) {
2915                $currentJump = $jumps[$uLevel];
2916            } else {
2917                $currentJump = 60000;
2918            }
2919        }
2920
2921        $u['User']['level'] = $uLevel;
2922        if ($uXp + $xpBonus < $firstJump) {
2923            $u['User']['xp'] += $xpBonus;
2924        } else {
2925            $u['User']['xp'] = $next;
2926        }
2927        $u['User']['nextlvl'] = $currentJump;
2928
2929        ClassRegistry::init('User')->save($u);
2930    }
2931
2932    public static function getPartitionRange($amountRemaining, $collectionSize, $partition) {
2933        if ($collectionSize > 0) {
2934            $amountPartitions = ceil($amountRemaining / $collectionSize);
2935        } else {
2936            return ['0', $collectionSize - 1];
2937        }
2938        if ($collectionSize > 0 && $amountRemaining % $collectionSize == 0) {
2939            return [ $partition * $collectionSize,  $partition * $collectionSize + $collectionSize - 1];
2940        }
2941        $amountCounter = 0;
2942        $amountFrom = 0;
2943        $amountTo = $collectionSize - 1;
2944        while ($amountRemaining > $collectionSize) {
2945            if ($partition == $amountCounter) {
2946                break;
2947            }
2948            $amountRemaining -= $collectionSize;
2949            $amountCounter++;
2950            $amountFrom += $collectionSize;
2951            $amountTo += $collectionSize;
2952        }
2953        $amountTo = $amountFrom + $collectionSize - 1;
2954        if ($partition >= $amountPartitions - 1) {
2955            $amountTo = $amountFrom + $amountRemaining - 1;
2956        }
2957        $a = [];
2958        $a[0] = $amountFrom;
2959        $a[1] = $amountTo;
2960
2961        return $a;
2962    }
2963
2964    /**
2965     * @param int $uid User ID
2966     * @return void
2967     */
2968    protected function handleSearchSettings($uid) {
2969        $this->loadModel('UserContribution');
2970        $uc = $this->UserContribution->find('first', ['conditions' => ['user_id' => $uid]]);
2971        if ($uc == null) {
2972            $uc = [];
2973            $uc['UserContribution']['user_id'] = $uid;
2974            $uc['UserContribution']['added_tag'] = 0;
2975            $uc['UserContribution']['created_tag'] = 0;
2976            $uc['UserContribution']['made_proposal'] = 0;
2977            $uc['UserContribution']['reviewed'] = 0;
2978            $uc['UserContribution']['score'] = 0;
2979            $this->UserContribution->create();
2980            $this->UserContribution->save($uc);
2981        }
2982        new TsumegoFilters();
2983    }
2984
2985    protected function signIn(array $user): void {
2986        Auth::init($user);
2987        $vs = $this->TsumegoStatus->find('first', ['conditions' => ['user_id' => $user['User']['id']], 'order' => 'created DESC']);
2988        if ($vs) {
2989            $this->Session->write('lastVisit', $vs['TsumegoStatus']['tsumego_id']);
2990        }
2991        $this->Session->write('texture', $user['User']['texture']);
2992        $this->Session->write('check1', $user['User']['id']);
2993    }
2994
2995    public function beforeFilter(): void {
2996        $this->loadModel('User');
2997        $this->loadModel('Activate');
2998        $this->loadModel('Tsumego');
2999        $this->loadModel('TsumegoRatingAttempt');
3000        $this->loadModel('Set');
3001        $this->loadModel('TimeModeAttempt');
3002        $this->loadModel('TsumegoStatus');
3003        $this->loadModel('Comment');
3004        $this->loadModel('UserBoard');
3005        $this->loadModel('TsumegoAttempt');
3006        $this->loadModel('AdminActivity');
3007        $this->loadModel('Achievement');
3008        $this->loadModel('AchievementStatus');
3009        $this->loadModel('AchievementCondition');
3010        $this->loadModel('SetConnection');
3011        $this->loadModel('Tag');
3012        $this->loadModel('TagName');
3013        $this->loadModel('Favorite');
3014
3015        Auth::init();
3016        $this->TimeMode->init();
3017
3018        $highscoreLink = 'highscore';
3019        $lightDark = 'light';
3020        $resetCookies = false;
3021        $levelBar = 1;
3022        $lastProfileLeft = 1;
3023        $lastProfileRight = 2;
3024        $hasFavs = false;
3025
3026        if (Auth::isLoggedIn()) {
3027            if (isset($_COOKIE['addTag']) && $_COOKIE['addTag'] != 0 && $this->Session->read('page') != 'set') {
3028                $newAddTag = explode('-', $_COOKIE['addTag']);
3029                $tagId = $newAddTag[0];
3030                $newTagName = $this->TagName->find('first', ['conditions' => ['name' => str_replace($tagId . '-', '', $_COOKIE['addTag'])]]);
3031                if ($newTagName) {
3032                    $saveTag = [];
3033                    $saveTag['Tag']['tag_name_id'] = $newTagName['TagName']['id'];
3034                    $saveTag['Tag']['tsumego_id'] = $tagId;
3035                    $saveTag['Tag']['user_id'] = Auth::getUserID();
3036                    $saveTag['Tag']['approved'] = 0;
3037                    $this->Tag->save($saveTag);
3038                }
3039                $this->set('removeCookie', 'addTag');
3040            }
3041            if (isset($_COOKIE['z_sess']) && $_COOKIE['z_sess'] != 0
3042            && strlen($_COOKIE['z_sess']) > 5) {
3043                Auth::getUser()['_sessid'] = $_COOKIE['z_sess'];
3044                Auth::saveUser();
3045            }
3046            if (Auth::getUser()['lastHighscore'] == 1) {
3047                $highscoreLink = 'highscore';
3048            } elseif (Auth::getUser()['lastHighscore'] == 2) {
3049                $highscoreLink = 'rating';
3050            } elseif (Auth::getUser()['lastHighscore'] == 3) {
3051                $highscoreLink = 'leaderboard';
3052            } elseif (Auth::getUser()['lastHighscore'] == 4) {
3053                $highscoreLink = 'highscore3';
3054            }
3055
3056            if (isset($_COOKIE['lastMode']) && $_COOKIE['lastMode'] != 0) {
3057                Auth::getUser()['lastMode'] = $_COOKIE['lastMode'];
3058                Auth::saveUser();
3059            }
3060            if (isset($_COOKIE['sound']) && $_COOKIE['sound'] != '0') {
3061                Auth::getUser()['sound'] = $_COOKIE['sound'];
3062                Auth::saveUser();
3063                unset($_COOKIE['sound']);
3064            }
3065            $this->set('ac', true);
3066            $this->set('user', Auth::getUser());
3067        }
3068
3069        if (isset($_COOKIE['lightDark']) && $_COOKIE['lightDark'] != '0') {
3070            $lightDark = $_COOKIE['lightDark'];
3071            if (Auth::isLoggedIn()) {
3072                // Convert string to integer for database storage
3073                $lightDarkInt = ($lightDark === 'light') ? 0 : 2;
3074                Auth::getUser()['lastLight'] = $lightDarkInt;
3075            }
3076        } elseif (Auth::isLoggedIn()) {
3077            if (Auth::getUser()['lastLight'] == 0
3078            || Auth::getUser()['lastLight'] == 1) {
3079                $lightDark = 'light';
3080            } else {
3081                $lightDark = 'dark';
3082            }
3083        }
3084
3085        if (Auth::isLoggedIn()) {
3086            $this->handleSearchSettings(Auth::getUserID());
3087            if (isset($_COOKIE['levelBar']) && $_COOKIE['levelBar'] != '0') {
3088                $levelBar = $_COOKIE['levelBar'];
3089                Auth::getUser()['levelBar'] = $levelBar;
3090            } elseif (Auth::getUser()['levelBar'] == 0
3091          || Auth::getUser()['levelBar'] == 'level') {
3092                $levelBar = 1;
3093            } else {
3094                $levelBar = 2;
3095            }
3096
3097            if (isset($_COOKIE['lastProfileLeft']) && $_COOKIE['lastProfileLeft'] != '0') {
3098                $lastProfileLeft = $_COOKIE['lastProfileLeft'];
3099                Auth::getUser()['lastProfileLeft'] = $lastProfileLeft;
3100            } else {
3101                $lastProfileLeft = Auth::getUser()['lastProfileLeft'];
3102                if ($lastProfileLeft == 0) {
3103                    $lastProfileLeft = 1;
3104                }
3105            }
3106            if (isset($_COOKIE['lastProfileRight']) && $_COOKIE['lastProfileRight'] != '0') {
3107                $lastProfileRight = $_COOKIE['lastProfileRight'];
3108                Auth::getUser()['lastProfileRight'] = $lastProfileRight;
3109            } else {
3110                $lastProfileRight = Auth::getUser()['lastProfileRight'];
3111                if ($lastProfileRight == 0) {
3112                    $lastProfileRight = 1;
3113                }
3114            }
3115        }
3116        $mode = 1;
3117        if (isset($_COOKIE['mode']) && $_COOKIE['mode'] != '0') {
3118            if ($_COOKIE['mode'] == 1) {
3119                $mode = 1;
3120            } else {
3121                $mode = 2;
3122            }
3123        }
3124
3125        if (Auth::isLoggedIn() && Auth::getUser()['mode'] == 2) {
3126            $mode = 2;
3127        }
3128
3129        if ($_COOKIE['sprint'] != 1) {
3130            $this->updateSprintCondition();
3131        }
3132        $correctSolveAttempt = false;
3133
3134        if (Auth::isLoggedIn()) {
3135            if (isset($_COOKIE['revelation']) && $_COOKIE['revelation'] != 0) {
3136                Auth::getUser()['revelation'] -= 1;
3137            }
3138
3139            if (!$this->request->is('ajax')) {
3140                $this->PlayResultProcessor->checkPreviousPlay($this->TimeMode);
3141            }
3142
3143            if (isset($_COOKIE['noScore']) && isset($_COOKIE['noPreId'])) {
3144                if ($_COOKIE['noScore'] != '0' && $_COOKIE['noPreId'] != '0') {
3145                    //$previosTsumegoX = $this->Tsumego->findById($_COOKIE['noPreId']);
3146                    //$previosTsumegoXsc = $this->SetConnection->find('first', array('conditions' => array('tsumego_id' => $_COOKIE['noPreId'])));
3147                    //$scoreArrX = explode('-', $this->decrypt($_COOKIE['noScore']));
3148
3149                    $utPreX = $this->TsumegoStatus->find('first', ['conditions' => ['tsumego_id' => $_COOKIE['noPreId'], 'user_id' => Auth::getUserID()]]);
3150                    if ($utPreX == null) {
3151                        $utPreX['TsumegoStatus'] = [];
3152                        $utPreX['TsumegoStatus']['user_id'] = Auth::getUserID();
3153                        $utPreX['TsumegoStatus']['tsumego_id'] = $_COOKIE['noPreId'];
3154                    }
3155                    if ($utPreX['TsumegoStatus']['status'] == 'W') {
3156                        $utPreX['TsumegoStatus']['status'] = 'C';
3157                    } else {
3158                        $utPreX['TsumegoStatus']['status'] = 'S';
3159                    }
3160                    $utPreX['TsumegoStatus']['created'] = date('Y-m-d H:i:s');
3161                    //$this->TsumegoStatus->save($utPreX);
3162                    //$sessionUts = $this->Session->read('loggedInUser.uts');
3163                    /*if (!$sessionUts) {
3164                    $sessionUts = [];
3165                    }
3166                    $sessionUts[$utPreX['TsumegoStatus']['tsumego_id']] = $utPreX['TsumegoStatus']['status'];
3167                    $this->Session->write('loggedInUser.uts', $sessionUts);*/
3168                }
3169            }
3170        }
3171        $boardNames = [];
3172        $enabledBoards = [];
3173        $boardPositions = [];
3174
3175        $boardNames[1] = 'Pine';
3176        $boardNames[2] = 'Ash';
3177        $boardNames[3] = 'Maple';
3178        $boardNames[4] = 'Shin Kaya';
3179        $boardNames[5] = 'Birch';
3180        $boardNames[6] = 'Wenge';
3181        $boardNames[7] = 'Walnut';
3182        $boardNames[8] = 'Mahogany';
3183        $boardNames[9] = 'Blackwood';
3184        $boardNames[10] = 'Marble 1';
3185        $boardNames[11] = 'Marble 2';
3186        $boardNames[12] = 'Marble 3';
3187        $boardNames[13] = 'Tibet Spruce';
3188        $boardNames[14] = 'Marble 4';
3189        $boardNames[15] = 'Marble 5';
3190        $boardNames[16] = 'Quarry 1';
3191        $boardNames[17] = 'Flowers';
3192        $boardNames[18] = 'Nova';
3193        $boardNames[19] = 'Spring';
3194        $boardNames[20] = 'Moon';
3195        $boardNames[21] = 'Apex';
3196        $boardNames[22] = 'Gold 1';
3197        $boardNames[23] = 'Amber';
3198        $boardNames[24] = 'Marble 6';
3199        $boardNames[25] = 'Marble 7';
3200        $boardNames[26] = 'Marble 8';
3201        $boardNames[27] = 'Marble 9';
3202        $boardNames[28] = 'Marble 10';
3203        $boardNames[29] = 'Jade';
3204        $boardNames[30] = 'Quarry 2';
3205        $boardNames[31] = 'Black Bricks';
3206        $boardNames[32] = 'Wallpaper 1';
3207        $boardNames[33] = 'Wallpaper 2';
3208        $boardNames[34] = 'Gold & Gray';
3209        $boardNames[35] = 'Gold & Pink';
3210        $boardNames[36] = 'Veil';
3211        $boardNames[37] = 'Tiles';
3212        $boardNames[38] = 'Mars';
3213        $boardNames[39] = 'Pink Cloud';
3214        $boardNames[40] = 'Reptile';
3215        $boardNames[41] = 'Mezmerizing';
3216        $boardNames[42] = 'Magenta Sky';
3217        $boardNames[43] = 'Tsumego Hero';
3218        $boardNames[44] = 'Pretty';
3219        $boardNames[45] = 'Hunting';
3220        $boardNames[46] = 'Haunted';
3221        $boardNames[47] = 'Carnage';
3222        $boardNames[48] = 'Blind Spot';
3223        $boardNames[49] = 'Giants';
3224        $boardNames[50] = 'Gems';
3225        $boardNames[51] = 'Grandmaster';
3226        $boardPositions[1] = [1, 'texture1', 'black34.png', 'white34.png'];
3227        $boardPositions[2] = [2, 'texture2', 'black34.png', 'white34.png'];
3228        $boardPositions[3] = [3, 'texture3', 'black34.png', 'white34.png'];
3229        $boardPositions[4] = [4, 'texture4', 'black.png', 'white.png'];
3230        $boardPositions[5] = [5, 'texture5', 'black34.png', 'white34.png'];
3231        $boardPositions[6] = [6, 'texture6', 'black.png', 'white.png'];
3232        $boardPositions[7] = [7, 'texture7', 'black34.png', 'white34.png'];
3233        $boardPositions[8] = [8, 'texture8', 'black.png', 'white.png'];
3234        $boardPositions[9] = [9, 'texture9', 'black.png', 'white.png'];
3235        $boardPositions[10] = [10, 'texture10', 'black34.png', 'white34.png'];
3236        $boardPositions[11] = [11, 'texture11', 'black34.png', 'white34.png'];
3237        $boardPositions[12] = [12, 'texture12', 'black34.png', 'white34.png'];
3238        $boardPositions[13] = [13, 'texture13', 'black34.png', 'white34.png'];
3239        $boardPositions[14] = [14, 'texture14', 'black34.png', 'white34.png'];
3240        $boardPositions[15] = [15, 'texture15', 'black.png', 'white.png'];
3241        $boardPositions[16] = [16, 'texture16', 'black34.png', 'white34.png'];
3242        $boardPositions[17] = [17, 'texture17', 'black34.png', 'white34.png'];
3243        $boardPositions[18] = [18, 'texture18', 'black.png', 'white.png'];
3244        $boardPositions[19] = [19, 'texture19', 'black34.png', 'white34.png'];
3245        $boardPositions[20] = [20, 'texture20', 'black34.png', 'white34.png'];
3246        $boardPositions[21] = [33, 'texture33', 'black34.png', 'white34.png'];
3247        $boardPositions[22] = [21, 'texture21', 'black.png', 'whiteKo.png'];
3248        $boardPositions[23] = [22, 'texture22', 'black34.png', 'white34.png'];
3249        $boardPositions[24] = [34, 'texture34', 'black.png', 'white.png'];
3250        $boardPositions[25] = [35, 'texture35', 'black34.png', 'white34.png'];
3251        $boardPositions[26] = [36, 'texture36', 'black.png', 'white.png'];
3252        $boardPositions[27] = [37, 'texture37', 'black34.png', 'white34.png'];
3253        $boardPositions[28] = [38, 'texture38', 'black38.png', 'white34.png'];
3254        $boardPositions[29] = [39, 'texture39', 'black.png', 'white.png'];
3255        $boardPositions[30] = [40, 'texture40', 'black34.png', 'white34.png'];
3256        $boardPositions[31] = [41, 'texture41', 'black34.png', 'white34.png'];
3257        $boardPositions[32] = [42, 'texture42', 'black34.png', 'white42.png'];
3258        $boardPositions[33] = [43, 'texture43', 'black34.png', 'white42.png'];
3259        $boardPositions[34] = [44, 'texture44', 'black34.png', 'white34.png'];
3260        $boardPositions[35] = [45, 'texture45', 'black34.png', 'white42.png'];
3261        $boardPositions[36] = [47, 'texture47', 'black34.png', 'white34.png'];
3262        $boardPositions[37] = [48, 'texture48', 'black34.png', 'white34.png'];
3263        $boardPositions[38] = [49, 'texture49', 'black.png', 'white.png'];
3264        $boardPositions[39] = [50, 'texture50', 'black34.png', 'white34.png'];
3265        $boardPositions[40] = [51, 'texture51', 'black34.png', 'white34.png'];
3266        $boardPositions[41] = [52, 'texture52', 'black34.png', 'white34.png'];
3267        $boardPositions[42] = [53, 'texture53', 'black34.png', 'white34.png'];
3268        $boardPositions[43] = [54, 'texture54', 'black54.png', 'white54.png'];
3269        $boardPositions[44] = [23, 'texture23', 'black.png', 'whiteFlower.png'];
3270        $boardPositions[45] = [24, 'texture24', 'black24.png', 'white24.png'];
3271        $boardPositions[46] = [25, 'texture25', 'blackGhost.png', 'white.png'];
3272        $boardPositions[47] = [26, 'texture26', 'blackInvis.png', 'whiteCarnage.png'];
3273        $boardPositions[48] = [27, 'texture27', 'black27.png', 'white27.png'];
3274        $boardPositions[49] = [28, 'texture28', 'blackGiant.png', 'whiteKo.png'];
3275        $boardPositions[50] = [29, 'texture29', 'blackKo.png', 'whiteKo.png'];
3276        $boardPositions[51] = [30, 'texture55', 'blackGalaxy.png', 'whiteGalaxy.png'];
3277
3278        $boardCount = 51;
3279
3280        if ($this->Session->check('texture') || (isset($_COOKIE['texture']) && $_COOKIE['texture'] != '0')) {
3281            $splitCookie = [];
3282            if (isset($_COOKIE['texture']) && $_COOKIE['texture'] != '0') {
3283                $splitCookie = str_split($_COOKIE['texture']);
3284                $textureCookies = $_COOKIE['texture'];
3285                Auth::getUser()['texture'] = $this->Session->read('texture');
3286                $this->Session->write('texture', $_COOKIE['texture']);
3287                $this->set('textureCookies', $textureCookies);
3288            } else {
3289                if (Auth::isLoggedIn()) {
3290                    $this->Session->write('texture', Auth::getUser()['texture']);
3291                }
3292                $textureCookies = $this->Session->read('texture');
3293                $splitTextureCookies = str_split($textureCookies);
3294                $splitTextureCookiesCount = count($splitTextureCookies);
3295                for ($i = 0; $i < $splitTextureCookiesCount; $i++) {
3296                    if ($splitTextureCookies[$i] == 2) {
3297                        $enabledBoards[$i + 1] = 'checked';
3298                    } else {
3299                        $enabledBoards[$i + 1] = '';
3300                    }
3301                }
3302            }
3303
3304            $splitCookieCount = count($splitCookie);
3305            for ($i = 0; $i < $splitCookieCount; $i++) {
3306                if ($splitCookie[$i] == 2) {
3307                    $enabledBoards[$i + 1] = 'checked';
3308                } else {
3309                    $enabledBoards[$i + 1] = '';
3310                }
3311            }
3312            if (Auth::isLoggedIn()) {
3313                Auth::saveUser();
3314            }
3315        }
3316
3317        if (!$this->Session->check('texture')) {
3318            $this->Session->write('texture', '222222221111111111111111111111111111111111111111111');
3319            $enabledBoards[1] = 'checked';
3320            $enabledBoards[2] = 'checked';
3321            $enabledBoards[3] = 'checked';
3322            $enabledBoards[4] = 'checked';
3323            $enabledBoards[5] = 'checked';
3324            $enabledBoards[6] = 'checked';
3325            $enabledBoards[7] = 'checked';
3326            $enabledBoards[8] = 'checked';
3327            $enabledBoards[9] = '';
3328            $enabledBoards[10] = '';
3329            $enabledBoards[11] = '';
3330            $enabledBoards[12] = '';
3331            $enabledBoards[13] = '';
3332            $enabledBoards[14] = '';
3333            $enabledBoards[15] = '';
3334            $enabledBoards[16] = '';
3335            $enabledBoards[17] = '';
3336            $enabledBoards[18] = '';
3337            $enabledBoards[19] = '';
3338            $enabledBoards[20] = '';
3339            $enabledBoards[21] = '';
3340            $enabledBoards[22] = '';
3341            $enabledBoards[23] = '';
3342            $enabledBoards[24] = '';
3343            $enabledBoards[25] = '';
3344            $enabledBoards[26] = '';
3345            $enabledBoards[27] = '';
3346            $enabledBoards[28] = '';
3347            $enabledBoards[29] = '';
3348            $enabledBoards[30] = '';
3349            $enabledBoards[31] = '';
3350            $enabledBoards[32] = '';
3351            $enabledBoards[33] = '';
3352            $enabledBoards[34] = '';
3353            $enabledBoards[35] = '';
3354            $enabledBoards[36] = '';
3355            $enabledBoards[37] = '';
3356            $enabledBoards[38] = '';
3357            $enabledBoards[39] = '';
3358            $enabledBoards[40] = '';
3359            $enabledBoards[41] = '';
3360            $enabledBoards[42] = '';
3361            $enabledBoards[43] = '';
3362            $enabledBoards[44] = '';
3363            $enabledBoards[45] = '';
3364            $enabledBoards[46] = '';
3365            $enabledBoards[47] = '';
3366            $enabledBoards[48] = '';
3367            $enabledBoards[49] = '';
3368            $enabledBoards[50] = '';
3369            $enabledBoards[51] = '';
3370        }
3371        $achievementUpdate = [];
3372        if ($this->Session->check('initialLoading')) {
3373            $achievementUpdate1 = $this->checkLevelAchievements();
3374            $achievementUpdate2 = $this->checkProblemNumberAchievements();
3375            $achievementUpdate3 = $this->checkRatingAchievements();
3376            $achievementUpdate4 = $this->checkTimeModeAchievements();
3377            $achievementUpdate5 = $this->checkDanSolveAchievements();
3378            $achievementUpdate = array_merge(
3379                $achievementUpdate1 ?: [],
3380                $achievementUpdate2 ?: [],
3381                $achievementUpdate3 ?: [],
3382                $achievementUpdate4 ?: [],
3383                $achievementUpdate5 ?: []
3384            );
3385            $this->Session->delete('initialLoading');
3386        }
3387
3388        if (count($achievementUpdate) > 0) {
3389            $this->updateXP(Auth::getUserID(), $achievementUpdate);
3390        }
3391
3392        $nextDay = new DateTime('tomorrow');
3393        if (Auth::isLoggedIn()) {
3394            Auth::getUser()['name'] = $this->checkPicture(Auth::getUser());
3395            $this->set('user', Auth::getUser());
3396        }
3397        $this->set('mode', $mode);
3398        $this->set('nextDay', $nextDay->format('m/d/Y'));
3399        $this->set('boardNames', $boardNames);
3400        $this->set('enabledBoards', $enabledBoards);
3401        $this->set('boardPositions', $boardPositions);
3402        $this->set('highscoreLink', $highscoreLink);
3403        $this->set('achievementUpdate', $achievementUpdate);
3404        $this->set('lightDark', $lightDark);
3405        $this->set('levelBar', $levelBar);
3406        $this->set('lastProfileLeft', $lastProfileLeft);
3407        $this->set('lastProfileRight', $lastProfileRight);
3408        $this->set('resetCookies', $resetCookies);
3409        $this->set('hasFavs', $hasFavs);
3410    }
3411
3412    public function afterFilter() {}
3413}